How do I evaluate the left-hand side of this binary expression?
Expression<Func<Person, bool>> expr = (x) => x.Birthday.AddMinutes(1) > DateTime.UtcNow;
If I call
System.Linq.Expressions.Expression.Lambda(expr.Left).Compile().DynamicInvoke()
I get the error message "variable 'x' of type '...' referenced from scope '', but it is not defined"
To be clear, I want to get the value of x.Birthday.AddMinutes(1) which is a InstanceMethodCallExpressionN
You need to capture the parameter (x
) from the original lambda to create a new lambda that uses that parameter.
var lambdaExpr = Expression.Lambda(((BinaryExpression)expr.Body).Left, expr.Parameters);
var lambdaFunc = lambdaExpr.Compile();
var result = lambdaFunc.DynamicInvoke(new Person() { Birthday = DateTime.Now});
// e.g. 2/12/2020 1:39:12 PM
Console.WriteLine(result);