Let's say I have a Predicate<T>
, and I want to call method foo with said predicate returning true, and I want to call method bar with a predicate returning false, how can I do this:
Predicate<int> p = i => i > 0
foo(p);
bar(!p); // obviously this doesn't work
If the predicate was a Func<int, bool> f
, I could just !f(i)
You can easily create a method to return an "inverted" predicate - you could even make it an extension method:
public static Predicate<T> Invert<T>(this Predicate<T> predicate)
{
// TODO: Nullity checking
return x => !predicate(x);
}
Then:
bar(p.Invert());
Basically it's exactly what you'd do if you had a Func<int, bool>
- there's nothing "magic" about either of those delegate types.
See more on this question at Stackoverflow