Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Expression from Func

Tags:

c#

generics

I have a Func<TCollection, T> in my code. I use it to select certain properties.

In a call to another method I need Expression<Func<TCollection, T>> as a parameter.

Is there any way to convert (or create from) Func<TCollection, T> to Expression<Func<TCollection, T>> ?

Thanx

like image 622
SolarX Avatar asked Feb 21 '12 12:02

SolarX


People also ask

What is the difference between expression and func C#?

An Expression<Func<>> is the representation of a function that has yet to be turned into code. A Func<> is an actual executable function. Using the former allows you to turn the expression into the appropriate function at the time that it is invoked.

What is expression C#?

An expression in C# is a combination of operands (variables, literals, method calls) and operators that can be evaluated to a single value. To be precise, an expression must have at least one operand but may not have any operator.


2 Answers

You can not recreate an expression based on a method since an expression needs to know the original statements, not IL. You can however create an Expresson which makes a method call to your func like:

Func<int> func = () => 1; Expression<Func<int>> expression = Expression.Lambda<Func<int>>(Expression.Call(func.Method)); 

Note however that systems like EF can't really work with this

like image 158
Polity Avatar answered Sep 27 '22 01:09

Polity


While you could just create an expression tree which calls your delegate, it's unlikely to be useful - because the delegate will basically be a black box as far as the code analyzing the expression tree is concerned. Assuming you're trying to use something like LINQ to SQL, the query analyzer will need to be able to peer into your logic to convert it to SQL - and it can't do that if it reaches a plain delegate.

You should probably change the code which comes up with the delegate in the first place, to create an expression tree instead.

like image 35
Jon Skeet Avatar answered Sep 25 '22 01:09

Jon Skeet