Convert Expression> to Expression> by

2019-04-28 16:57发布

问题:

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

回答1:

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);
}