49

I will keep it really simple,

How do I get expression tree out of lambda??

or from query expression ?

Prashant Cholachagudda
  • 13,012
  • 23
  • 97
  • 162

4 Answers4

68

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.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
11

Konrad's reply is exact. You need to assign the lambda expression to Expression<Func<...>> in order for the compiler to generate the expression tree. If you get a lambda as a Func<...>, Action<...> or other delegate type, all you have is a bunch of IL instructions.

If you really need to be able to convert an IL-compiled lambda back into an expression tree, you'd have to decompile it (e.g. do what Lutz Roeder's Reflector tool does). I'd suggest having a look at the Cecil library, which provides advanced IL manipulation support and could save you quite some time.

Pierre Arnaud
  • 10,212
  • 11
  • 77
  • 108
8

Just to expand on Konrad's answer, and to correct Pierre, you can still generate an Expression from an IL-compiled lambda, though it's not terribly elegant. Augmenting Konrad's example:

// Gives you a lambda:
Func<int, int> f = x => x * 2;

// Gives you an expression tree:
Expression<Func<int, int>> g = x => f(x);
joniba
  • 3,339
  • 4
  • 35
  • 49
  • 17
    This **does not** give you the expression tree of the original lamda, it gives you a **new** expression tree that calls the delegate. Nothing more. – Aidiakapi Apr 16 '13 at 12:11
  • The question is not specific on getting an *equivalent* expression. For in-memory LINQ this provides identical functionality. Of course it could not be parsed properly by any LINQ provider. – joniba Aug 29 '17 at 10:52
0

A runtime alternative is to use this project - https://github.com/kostat/XLinq :

// Gives you a lambda:
Func<int, int> f = x => x * 2;

// Gives you an expression tree:
Expression<Func<int, int>> g = ExpressionTree.Parse(f);
Konstantin Triger
  • 1,576
  • 14
  • 11