Understanding Expression Tree and Parameter Evaluation

强颜欢笑 提交于 2019-12-04 15:36:14

I think the code from the blog post has exactly what you need: all you have to do is to use valueSelector.Body instead of your Expression.Constant() and also add the original parameter to the generated expression:

public static Expression<Func<TElement, bool>>
    BuildRangeExpression<TElement, TValue>(
    Expression<Func<TElement, TValue>> valueSelector,
    IEnumerable<Tuple<TValue, TValue>> values)
{
    var p = valueSelector.Parameters.Single();

    var equals = values.Select(
        tuple =>
        Expression.AndAlso(
            Expression.GreaterThanOrEqual(
                valueSelector.Body, Expression.Constant(tuple.Item1)),
            Expression.LessThanOrEqual(
                valueSelector.Body, Expression.Constant(tuple.Item2))));

    var body = equals.Aggregate(Expression.OrElse);

    return Expression.Lambda<Func<TElement, bool>>(body, p);
}

Use Expression.Parameter.

Create a parameter:

var param = Expression.Parameter(typeof(TElement), "arg")

Instead of Expression.Constant(testvalue), you will need to put param.

Then, you need to do:

var result = Expression.Lambda<Func<TElement, bool>>(final, param).Compile() 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!