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

孤人 提交于 2019-12-07 03:29:07

问题


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


来源:https://stackoverflow.com/questions/3157905/convert-expressionfunct-t2-bool-to-expressionfunct2-bool-by-introduci

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!