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

Time:05-31

I have this Expression

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

And Now I want to eliminate/insert the value for the int value

like

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

the result should be a

Expression<Func<TEntity, bool>>

without the int parameter

thx

CodePudding user response:

You can create a new expression by replacing parameter in the body and creating new lambda expression with one parameter. For example using this replacer (or take ReplacingExpressionVisitor if you are using EF Core 3.0 ):

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

And modify expression:

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]);
  • Related