How to invert System.Predicate <T>

Let's say I have Predicate<T>

and I want to call the method foo with the specified predicate returning true and I want to call the method panel with the predicate returning false, how can I do this:

Predicate<int> p = i => i > 0
foo(p);
bar(!p); // obviously this doesn't work

      

If there was a predicate Func<int, bool> f

, I could just!f(i)

+3


source to share


2 answers


You can easily create a method to return an "inverted" predicate - you can 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());

      

This is basically exactly what you would do if you had Func<int, bool>

- there is nothing "magic" about any of these types of delegates.

+7


source


You can wrap the predicate in a lambda.



bar(x => !p(x));

      

+1


source







All Articles