Negating Func<T, bool> in lambda expression

asp.net, c#

Solution

Func<T, bool> expr = x => x.Prop != 1;

Func<T, bool> negativeExpr = value => !expr(value);

or

somelist = somelist.Where(value => !expr(value));

When using expression trees the following will do the trick:

Expression<Func<T, bool>> expr = x => x.Prop != 1;

var negativeExpr = Expression.Lambda<Func<T, bool>>(
    Expression.Not(expr.Body), 
    expr.Parameters);

somelist = somelist.Where(negativeExpr);

To make your life easier, you can create the following extension methods:

public static Func<T, bool> Not<T>(
    this Func<T, bool> predicate)
{
    return value => !predicate(value);
}

public static Expression<Func<T, bool>> Not<T>(
    this Expression<Func<T, bool>> expr)
{
    return Expression.Lambda<Func<T, bool>>(
        Expression.Not(expr.Body), 
        expr.Parameters);
}

Now you can do this:

somelist = somelist.Where(expr.Not());

Problem

``` Func<T, bool> expr = x => x.Prop != 1; somelist = somelist.Where(expr); ``` So far so good. But I would like to negate `expr` like this: ``` somelist = somelist.Where(!expr); ``` Which result in a compile error: `Cannot apply ! operator to operand of type Func<T, bool>`. Do I have to create another expression variable for this? ``` Func<T, bool> expr2 = x => x.Prop == 1; ```

Original source

Related problems