Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Expression<Func<T, T2, bool>> to Expression<Func<T2, bool>> by introducing a constant for T

I have an expression in the format of Expression<Func<T, T2, bool>> that I need to convert into an expression on the format of Expression<Func<T2, bool>> by replacing the T in the first expression with a constant value.

I need this to stay as an expression so I can't just Invoke the expression with a constant as the first parameter.

I've looked at the other questions here about expression trees but I can't really find a solution to my problem. I suspect I have to walk the expression tree to introduce the constant and remove one parameter but I don't even know where to start at the moment. :(

like image 931
Kristoffer L Avatar asked Jul 01 '10 12:07

Kristoffer L


1 Answers

You can use Expression.Invoke to create a new lambda expression that calls the other:

static Expression<Func<T2, bool>> PartialApply<T, T2>(Expression<Func<T, T2, bool>> expr, T c)
{
    var param = Expression.Parameter(typeof(T2), null);
    return Expression.Lambda<Func<T2, bool>>(
        Expression.Invoke(expr, Expression.Constant(c), param), 
        param);
}
like image 161
Quartermeister Avatar answered Sep 19 '22 17:09

Quartermeister