C# – How to convert Func to Expression>

cc#-4.0expression-treeslambdalinq

I have a Func like this :

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

How I can convert it to :

 Expression<Func<MyClass, bool>>

Best 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.