views:

44

answers:

2

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. :(

A: 

I suspect I have to walk the expression tree to introduce the constant and remove one parameter.

Correct.

Mau
+2  A: 

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);
}
Quartermeister
Works like a charm, and is a lot easier than walking the entire expression three. Thank you.
Kristoffer L