1

Is there an inverse operation to Expression.Lambda<...>(originalExpression, parameterExpression) that would return me the original expression?

Context:

I am creating a lambda expression using the lambda syntax (not using the Expression class at all) like this:

 return item => item.Something

In a different layer of the application, I would like to "un-lambda" this expression, apply

expression= Expression.Not(expression);

to it and then wrap it to a lambda again.

Is this possible?

Ondrej Janacek
  • 12,486
  • 14
  • 59
  • 93
Tomas Grosup
  • 6,396
  • 3
  • 30
  • 44

1 Answers1

4

LambdaExpression.Body is your original expression, so you can do

var inverted = Expression.Lambda(Expression.Not(lambda.Body), lambda.Parameters);
Jon
  • 428,835
  • 81
  • 738
  • 806
  • Thank you! I was struggling with the parameters, I was passing a new ParameterExpression (same count and types of arguments) in the Lambda call and apparently I have to pass in the very same instance of parameters that the lambda was using. – Tomas Grosup Dec 06 '13 at 12:59
  • @TomasGrosup: [I had that problem myself](http://stackoverflow.com/q/2797261/50079) in the past ;-) – Jon Dec 06 '13 at 13:02