0

I have this code:

public static List<Phrase> selectedPhrases;

and

if  (!App.selectedPhrases.Any(x => x.Viewed == false))
                return;

Is there any way that I could change the way I declare selectedPhrases so that I could do that last check in this way:

if  (App.selectedPhrases.AllViewed())
    return;

I heard about extension methods but is that possible to create one for a List like in my code?

Alan2
  • 23,493
  • 79
  • 256
  • 450

2 Answers2

6

You can write extension method on List, for your example, Phrase

public static class Extension
{
    public static bool AllViewed(this List<Phrase> source)
    {
        return source.All(x=>x.Viewed)
    }
}

Btw, You don't need to check !Any(x=>c.Viewed==false), there is the option to use .All() Extension method as shown in the code above

You can read more on the syntax of extension methods here.

You might be also interested to read on how Linq extension methods are implemented by looking at some of source code at referencesource .

Anu Viswan
  • 17,797
  • 2
  • 22
  • 51
  • 3
    It’s a good answer and I know OP asked for this, but I would argue that introducing an extension method `AllViewed()` that only does `All(x=>x.Viewed)` doesn’t really provide a benefit as the latter shows the intent quite well and isn’t much longer anyway. – ckuri Feb 03 '19 at 13:30
  • 1
    @ckuri True, may be OP was unsure about All() and had struck to Any. That's why i thought i would mentioned about All as well in the answer. But like you said, All(x=>x.Viewed) does the job well and extension method might not be quite required in this particular scenario. – Anu Viswan Feb 03 '19 at 13:36
1

You can create an extension method in a static class:

public static class PhraseExtensions
{
    public static bool AllViewed(this List<Phrase> phrases)
    {
        return !phrases.Any(p => !p.Viewed);
        // phrases.All(p => p.Viewed); would be better suited.
    }
}

See the documentation about extensions here: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/extension-methods

Philipp Grathwohl
  • 2,726
  • 3
  • 27
  • 38