Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invert the Expression<Func<T, bool>>

I'm writing the expression extensions method which must inverse the bool-typed lambda expression.

Here is what I am doing:

public static Expression<Func<T, bool>> Inverse<T>(this Expression<Func<T, bool>> e)
{
    return Expression.Lambda<Func<T, bool>>(Expression.Not(e));
}

But this raises an exception, that unary operator is NOT not defined for the type Func<int,bool>. I also tried this:

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

But getting this: Incorrent number of parameters supplied for lambda declaration.

like image 309
AgentFire Avatar asked Dec 17 '12 09:12

AgentFire


1 Answers

Fortunately, this is solved this way:

public static Expression<Func<T, bool>> Inverse<T>(this Expression<Func<T, bool>> e)
{
    return Expression.Lambda<Func<T, bool>>(Expression.Not(e.Body), e.Parameters[0]);
}

Which indicates that .Lambda<> method needs a parameter, which we need to pass it from source expression.

like image 125
AgentFire Avatar answered Oct 02 '22 18:10

AgentFire