Cancel `.Where ()` LINQ Expression

I understand that you can do the following:

enumerable.Where(MethodGroup).DoSomething();

and this is achieved by the same:

enumerable.Where(x => MyMethod(x)).DoSomething();

However, I want to achieve this and select the elements where the method returns false. Obviously, how to do this for the second case:

enumerable.Where(x => !MyMethod(x)).DoSomething();

However, for the first, this is not the case, since you cannot apply the operator !to MethodGroup. Is it possible to achieve such an effect " .WhereNot" using the MethodGroupssame way, or do I need to roll my own (or use lambda)?

+3
source share
5 answers

You can create a helper method:

public static Func<T, bool> Not<T>(Func<T, bool> method) 
{
    return x => !method(x);
} 

Then use will be very similar to what you want:

someEnumerable.Where(Not(MyMethod)).DoSomething();
+5
source

Except

yourList.Except(yourList.Where(MethodGroup)).DoSomething();
+2

, , . , :

someList.Where(x => !MyMethod(x)).DoSomething();

, , .

. , . , - , , , .

+2

, LINQ. - , .

, , .

public static IEnumerable<TSource> WhereNot<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
{
    return source.Where(x => !predicate(x));
}

var inverseResult = lst.WhereNot(MyMethod);
+1

Where SkipWhile.

enumerable.SkipWhile(x => MyMethod(x)).DoSomething();
0

Source: https://habr.com/ru/post/1675605/


All Articles