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)?
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);
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With