How to convert Func to Expression>

c# c#-4.0 expression-trees lambda linq

Question

I have a Func like this :

 Func<MyClass, bool> func = x=>Id == 5;

How I can convert it to :

 Expression<Func<MyClass, bool>>

Accepted Answer

Try this:

Func<MyClass, bool> func = x=>Id == 5;
Expression<Func<MyClass, bool>> expr = mc => func(mc);

Popular Answer

You can just write:

Expression<Func<MyClass,bool>> expr = x=>Id == 5;

This will set expr to be an expression tree for Id == 5.

If you do:

Func<MyClass, bool> func = x=>Id == 5;
Expression<Func<MyClass, bool>> expr = mc => func(mc);

Then this will set expr to be an expression tree for a call to func, not an expression tree for the body of func.



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why