Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a LambdaExpression to typed Expression<Func<T, T>>

Tags:

I'm dynamically building linq queries for nHibernate.

Due to dependencies, I wanted to cast/retrieve the typed expression at a later time, but I have been unsuccessfull so far.

This is not working (the cast is supposed to happen elsewhere):

var funcType = typeof (Func<,>).MakeGenericType(entityType, typeof (bool)); var typedExpression =  (Func<T, bool>)Expression.Lambda(funcType, itemPredicate, parameter); //Fails 

This is working:

var typedExpression = Expression.Lambda<Func<T, bool>>(itemPredicate, parameter); 

Is it possible to get the 'encapsulated' typed expression from a LambdaExpression?

like image 710
Larantz Avatar asked Apr 25 '13 11:04

Larantz


People also ask

What are lambda expressions C#?

C# lambda expression is a syntax to create delegates or expression trees. It is a very powerful syntactic sugar making C# functional.

What is lambda expression in C# with example?

The expression num => num * 5 is a lambda expression. The => operator is called the "lambda operator". In this example, num is an input parameter to the anonymous function, and the return value of this function is num * 5 . So when multiplyByFive is called with a parameter of 7 , the result is 7 * 5 , or 35 .

What is lambda expression in Linq?

The term 'Lambda expression' has derived its name from 'lambda' calculus which in turn is a mathematical notation applied for defining functions. Lambda expressions as a LINQ equation's executable part translate logic in a way at run time so it can pass on to the data source conveniently.


1 Answers

var typedExpression =     (Func<T, bool>)Expression.Lambda(funcType, itemPredicate, parameter); //Fails 

This is not surprising, as you have to Compile a LambdaExpression in order to get an actual delegate that can be invoked (which is what Func<T, bool> is).

So this would work, but I 'm not sure if it is what you need:

// This is no longer an expression and cannot be used with IQueryable var myDelegate =     (Func<T, bool>)     Expression.Lambda(funcType, itemPredicate, parameter).Compile(); 

If you are not looking to compile the expression but instead to move an expression tree around, then the solution is to instead cast to an Expression<Func<T, bool>>:

var typedExpression = (Expression<Func<T, bool>>)                        Expression.Lambda(funcType, itemPredicate, parameter); 
like image 152
Jon Avatar answered Sep 17 '22 09:09

Jon