Search code examples
c#expression-trees

Is there an inverse operation to Expression.Lambda?


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?


Solution

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

    var inverted = Expression.Lambda(Expression.Not(lambda.Body), lambda.Parameters);