我有这个表情
public Expression<Func<TEntity, int, bool>> FilterExpr
现在我想消除/插入int值的值
喜欢
int i = 12;
//Pseudo Code which sets the value of the second Parameter
FilterExpr.Arg2 = i;
结果应该是
Expression<Func<TEntity, bool>>
不带int参数
thx公司
我有这个表情
public Expression<Func<TEntity, int, bool>> FilterExpr
现在我想消除/插入int值的值
喜欢
int i = 12;
//Pseudo Code which sets the value of the second Parameter
FilterExpr.Arg2 = i;
结果应该是
Expression<Func<TEntity, bool>>
不带int参数
thx公司
可以通过替换主体中的参数并使用一个参数创建新的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]);