Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Negate `.Where()` LINQ Expression

Tags:

c#

lambda

linq

I understand that you can do the following:

enumerable.Where(MethodGroup).DoSomething();

and that this achieves the same thing as:

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

However, I wish to achieve the inverse of this and to select the items where the method returns false. It is obvious how to do this for the second case:

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

Yet, for the first, this is not the case as you cannot apply the ! operator to a MethodGroup. Is it possible to achieve this sort of ".WhereNot" effect with MethodGroups in a similar fashion or do I have to roll my own (or use lambdas)?

like image 865
Persistence Avatar asked Apr 25 '17 11:04

Persistence


3 Answers

There is no direct way to do this from the set of methods provided in LINQ. Even if you somehow achieve that, it won't be an efficient one.

Like you contemplated, a new one needs to be made like this

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

and use it like

var inverseResult = lst.WhereNot(MyMethod);
like image 172
Nikhil Agrawal Avatar answered Nov 02 '22 23:11

Nikhil Agrawal


You can create a helper method:

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

Then the usage will be very similar to what you want:

someEnumerable.Where(Not(MyMethod)).DoSomething();
like image 8
vyrp Avatar answered Nov 02 '22 23:11

vyrp


You could use Except to achieve this

yourList.Except(yourList.Where(MethodGroup)).DoSomething();
like image 2
Liviu Boboia Avatar answered Nov 03 '22 00:11

Liviu Boboia