Build a specific LINQ expression based on another LINQ expression and a value

前提是你 提交于 2019-12-06 09:43:01

You need to write an ExpressionVisitor that replaces the ParameterExpression with a ConstantExpression.

It would look something like

protected override Expression VisitParameter(ParameterExpression node) {
    if (node.Name == "filterVal")
        return Expression.Constant(something);
    return node;
}

In case it's useful the way I solved it was:

public class MyVisitor : ExpressionVisitor
{
    protected override Expression VisitParameter(ParameterExpression node)
    {
        Console.WriteLine("Visiting Parameter: " + node.Name);
        if (node.Name == "filterVal")
        {
            return Expression.Constant("John");
        }
        return node;
    }
}

Expression<Func<MyClass, string, bool>> filterExpression = (x, filterVal) => x.DisplayName.Contains(filterVal);
var filterExpBody = (new MyVisitor()).Visit(filterExpression.Body);
Expression<Func<MyClass, bool>> filter = Expression.Lambda<Func<MyClass, bool>>(filterExpBody, filterExpression.Parameters[0]);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!