Evaluate C# expression inside another expression

c# expression-trees linq-to-sql

Question

I want to use an expression in another one:

Expression<Func<double, double>> f = x => x * x * 27 + blah ... expression with x;

Expression<Func<double, double>> g = y => 3 + 8 * f.Compile()(y) * y * blah... expression with y and f(y);

This will not work when sent to LINQ to SQL because f.Compile() is unknown to SQL.

How do you evaluate the expression f on the variable y without compiling it, but still using normal syntax to define g?

I don't want to have to define all of g with some unreadable Expression.Add/Expression.Multiply etc. statements.

Thanks.

Accepted Answer

Take a look at Calling functions in LINQ queries and LINQ Extensions project. CLinq part is irrelevant to your question, but it also includes LinqExt library, which is just what are you looking for. The same approach is also used by LinqKit which also provides other useful extensions for Linq.




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