Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert between Linq expressions with different return types?

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.

like image 976
Leo Avatar asked Nov 22 '12 03:11

Leo


1 Answers

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);
like image 175
Ani Avatar answered Oct 16 '22 13:10

Ani