views:

92

answers:

1

Hi

Given the following

Expression<Func<T,bool>> matchExpression;

How can i create another expression that is a 'not' of the existing one.

i have tried

Expression<Func<T, bool>> func3 = (i) => !matchExpression.Invoke(i);

but this is not supported by the entity framework...

Regards

+8  A: 

You have to recreate a new lambda, and negate the body of the original one:

Expression<Func<T, bool>> not = Expression.Lambda<Func<T, bool>> (
    Expression.Not (matchExpression.Body),
    matchExpression.Parameters [0]);
Jb Evain
That is better; I was having a brain-fart ;p
Marc Gravell
(you could just pass in matchExpression.Parameters - it would be the same)
Marc Gravell
@Marc: Sure thing. But in that specific case, I like that it expresses the intent to negate the predicate with one parameter.
Jb Evain
Also, after this question, I ended up adding a way to negate a predicate in Mono.Linq.Expressions' PredicateBuilder: http://github.com/jbevain/mono.linq.expressions So thanks Richard :)
Jb Evain