表达式<Func<TEntity, int, bool> 设置int值

Expression<Func<TEntity, int, bool> set the int value

我有这个表达式

 public Expression<Func<TEntity, int, bool>> FilterExpr

而现在我想eliminate/insert int 值的值

喜欢

int i = 12;
//Pseudo Code which sets the value of the second Parameter
FilterExpr.Arg2 = i;

结果应该是

Expression<Func<TEntity, bool>>

没有int参数

感谢

您可以通过替换正文中的参数并使用一个参数创建新的 lambda 表达式来创建新的表达式。例如使用此替换器(如果您使用的是 EF Core 3.0+,则采用 ReplacingExpressionVisitor):

public static class ExpressionExt
{
    public static Expression ReplaceParameter(this Expression expression, ParameterExpression source, Expression target)
    {
        return new ParameterReplacingVisitor { Source = source, Target = target }.Visit(expression);
    }

    class ParameterReplacingVisitor : ExpressionVisitor
    {
        public ParameterExpression Source;
        public Expression Target;
        protected override Expression VisitParameter(ParameterExpression node)
        {
            return node == Source ? Target : base.VisitParameter(node);
        }
    }
}

并修改表达式:

var withReplaced = FilterExpr.Body.ReplaceParameter(
    FilterExpr.Parameters[1], // replace second parameter 
    Expression.Constant(42)); // with some constant
// build new expression with only one parameter by reusing first parameter of original one
var result = Expression.Lambda<Func<MyClass, bool>>(withReplaced, FilterExpr.Parameters[0]);