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>>
1
8
2/16/2013 5:52:32 AM

Accepted Answer

Try this:

Func<MyClass, bool> func = x=>Id == 5;
Expression<Func<MyClass, bool>> expr = mc => func(mc);
4
2/16/2013 5:48:10 AM

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.



Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow