Search code examples
c#lambdaexpression-trees

Lambda to Expression tree conversion


I will keep it really simple,

How do I get expression tree out of lambda??

or from query expression ?


Solution

  • You must assign the lambda to a different type:

    // Gives you a delegate:
    Func<int, int> f = x => x * 2;
    // Gives you an expression tree:
    Expression<Func<int, int>> g = x => x * 2;
    

    The same goes for method arguments. However, once you've assigned such a lambda expression to a Func<> type, you can't get the expression tree back.