简体   繁体   中英

Negate `.Where()` LINQ Expression

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

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

您可以使用Except来实现此目的

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM