Negate `.Where()` LINQ Expression

As far as I know there are no built in ways to do this so either roll your own solution. Or just use the lambda which I personally don't see anything wrong with:

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

This is also better than the other answer as it doesn't iterate over the collection twice.

Note just using the lambda makes your code more explicit than rolling your own method or using some workaround. In this case, for something as simple as this, I think it would be better to stick with the lambda and not add unnecessary obfuscation to your code.


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();

You could use Except to achieve this

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

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);

Tags:

C#

Linq

Lambda