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
.
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.
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