Create the logical inverse of an expression using Linq.

c# expression-trees linq

Question

I would like to create a method that accepts an Expression<Func<T, bool>> and creates the logical inverse of it (i.e. it would return false where it would have returned true, and vice versa. This is much harder than I thought. This is where I am up to:

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

This compiles fine but throws the following Exception when called:

Test method Tests.Common.Unit.LinqPredicateBuilderTests.CanInverseAPredicate threw exception: 
System.ArgumentException: Incorrect number of parameters supplied for lambda declaration

I have no idea what I'm doing. Could anyone fill in the blanks?

1
9
2/19/2013 2:09:59 AM

Accepted Answer

You're calling Expression.Lambda to create an expression with no parameters at all, when you should be forwarding the single parameter of the source expression.

Note that we are trying to create an Expression<Func<T, bool>> and not an Expression<Func<bool>>.

Try this instead:

return Expression.Lambda<Func<T, bool>>(Expression.Not(expression.Body),
                                        expression.Parameters);
18
11/7/2011 10:49:20 AM


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow