Introduction:
Case 1: Use the existing expression tree to build a new expression tree
Expression<Func<string, bool>> lambda0 = item => item.Length > 2; Expression<Func<string, bool>> lambda1 = item => item.Length < 4;
The above two expressions are merged into one Item => item.Length> 2 && item.Length < . 4
You can not directly use the following method of constructing this new expression tree, as the information before the Body Parameter with
public Func<string, bool> ReBuildExpression(Expression<Func<string, bool>> lambd0, Expression<Func<string, bool>> lambd1) { parameter = Expression.Parameter(typeof(string), "name"); Expression left = lambd0.Body; Expression right = lambd1.Body; BinaryExpression expression = Expression.AndAlso(left, right); Expression<Func<string, bool>> lambda = Expression.Lambda<Func<string, bool>>(expression, parameter); return lambda.Compile(); }
Use only ExpressionVisitor modify the expression will be replaced with a new Parameter before
public class SetParamExpressionVisitor : ExpressionVisitor { public ParameterExpression Parameter { get; set; } public SetParamExpressionVisitor() { } public SetParamExpressionVisitor(ParameterExpression parameter) { this.Parameter = parameter; } public Expression Modify(Expression exp) { return this.Visit(exp); } protected override Expression VisitParameter(ParameterExpression parameter) { return this.Parameter; } }
public static Func<string, bool> AndAlsoExpression(Expression<Func<string,bool>> exp1,Expression<Func<string, bool>> exp2) { var parameter = Expression.Parameter(typeof(string), "name"); SetParamExpressionVisitor visitor = new SetParamExpressionVisitor(parameter); var newExp1 = visitor.Modify(exp1.Body); var newExp2 = visitor.Modify(exp2.Body); var newBodyExp = Expression.AndAlso(newExp1, newExp2); return Expression.Lambda<Func<string, bool>>(newBodyExp, parameter).Compile(); }
transfer:
Expression<Func<string, bool>> exp1 = item => item.Length > 2; Expression<Func<string, bool>> exp2 = item => item.Length < 4; Func<string,bool> func = AndAlsoExpression(exp1, exp2); bool b = func("aaaa");//false
Reference: https://www.cnblogs.com/FlyEdward/archive/2010/12/06/Linq_ExpressionTree7.html
To be continued ...