Search code examples
c#linqlinq-expressions

evaluate a LambdaExpression?


I'm making a LINQ lambda expression:

 Expression<Func<double, double, double>> add = (x, y) => x + y;

But now how would I evaluate it, say to find 2+3?


Solution

  • This should work for you:

    var sum = add.Compile()(2,3);
    

    There is some case your Expression does not have generic types, you have to use DynamicInvoke to execute it because the Compile() then will return a Delegate:

    someNonGenericExpression.Compile().DynamicInvoke(2,3);