使用值展平表达参数

时间:2018-10-10 15:36:55

标签: c# iqueryable

我在课程中拥有此属性

final JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, JRBeanCollectionDataSource(fields));

我需要将字符串参数替换为运行时已知的值,并将其隐藏在其中:

public Expression<Func<T, string, bool>> FilterExp { get; set; }

所以我可以将其与IQueryable一起使用。

这是设置过滤器时的样子:

Expression<Func<T, bool>>

更改表达式的最佳方法是什么?

1 个答案:

答案 0 :(得分:1)

我想到了这个,它似乎正在起作用:

protected class ParameterReplacer : ExpressionVisitor
{
    private ParameterExpression parameterExpression;
    private string newValue;

    public ParameterReplacer(ParameterExpression parameterExpression, string newValue)
    {
        this.parameterExpression = parameterExpression;
        this.newValue = newValue;
    }

    public override Expression Visit(Expression node)
    {
        if (node == parameterExpression)
            return Expression.Constant(this.newValue);

        return base.Visit(node);
    }
}

在我的代码中,我像这样使用它:

var replacer = new ParameterReplacer(FilterExp.Parameters[1], Filter);
var newBody = replacer.Visit(FilterExp.Body);
var exp = Expression.Lambda<Func<T, bool>>(newBody, FilterExp.Parameters[0]);
return SourceData.Where(exp);