How to convert between Linq expressions with different return types?

.net c# expression-trees linq linq-expressions

Question

I'm having a headache trying to convert the following linq expression.

    Expression<Func<T, object>>

to the following linq expression...

    Expression<Func<T, U>>

In the example above the object is always of type U.

I know how easy it could to convert/cast between parameter types but I'm not too sure how to cast between return types.

1
8
10/8/2013 2:03:15 PM

Accepted Answer

You'll need to create a new expression by:

  1. Using Expression.Convert over the source expression's body to create the result's body.
  2. Using this body and reusing the parameters of the source expression to create the transformed lambda expression with Expression.Lambda.

Try this:

Expression<Func<T, object>> source = ...

var resultBody = Expression.Convert(source.Body, typeof(U));    
var result = Expression.Lambda<Func<T, U>>(resultBody, source.Parameters);
8
2/25/2013 1:27:37 PM

Popular Answer

My case was converting interface input type to the concrete type for my MongoDB generic repository.

I was converting from

Expression<Func<TIModel, bool>> iFilter

to

Expression<Func<TModel, bool>> filter

I just inspired from Ani's answer and converted like:

var filter = Expression.Lambda<Func<TModel, bool>>(iFilter.Body, iFilter.Parameters);


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