废话不多说,直接上代码 复制可
1 internal class NewExpressionVisitor : ExpressionVisitor 2 { 3 public ParameterExpression _NewParameter { get; private set; } 4 public NewExpressionVisitor(ParameterExpression param) 5 { 6 this._NewParameter = param; 7 } 8 public Expression Replace(Expression exp) 9 { 10 return this.Visit(exp); 11 } 12 protected override Expression VisitParameter(ParameterExpression node) 13 { 14 return this._NewParameter; 15 } 16 } 17 public static class ExpressionExt 18 { 19 /// <summary> 20 /// 合并表达式 expr1 AND expr2 21 /// </summary> 22 /// <typeparam name="T"></typeparam> 23 /// <param name="expr1"></param> 24 /// <param name="expr2"></param> 25 /// <returns></returns> 26 public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> expr1, Expression<Func<T, bool>> expr2) 27 { 28 if (expr1 == null) 29 return expr2; 30 else if (expr2 == null) 31 return expr1; 32 33 //return Expression.Lambda<Func<T, bool>>(Expression.AndAlso(expr1.Body, expr2.Body), expr1.Parameters); 34 ParameterExpression newParameter = Expression.Parameter(typeof(T), "c"); 35 NewExpressionVisitor visitor = new NewExpressionVisitor(newParameter); 36 37 var left = visitor.Replace(expr1.Body); 38 var right = visitor.Replace(expr2.Body); 39 var body = Expression.And(left, right); 40 return Expression.Lambda<Func<T, bool>>(body, newParameter); 41 42 } 43 /// <summary> 44 /// 合并表达式 expr1 or expr2 45 /// </summary> 46 /// <typeparam name="T"></typeparam> 47 /// <param name="expr1"></param> 48 /// <param name="expr2"></param> 49 /// <returns></returns> 50 public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> expr1, Expression<Func<T, bool>> expr2) 51 { 52 if (expr1 == null) 53 return expr2; 54 else if (expr2 == null) 55 return expr1; 56 57 ParameterExpression newParameter = Expression.Parameter(typeof(T), "c"); 58 NewExpressionVisitor visitor = new NewExpressionVisitor(newParameter); 59 60 var left = visitor.Replace(expr1.Body); 61 var right = visitor.Replace(expr2.Body); 62 var body = Expression.Or(left, right); 63 return Expression.Lambda<Func<T, bool>>(body, newParameter); 64 } 65 public static Expression<Func<T, bool>> Not<T>(this Expression<Func<T, bool>> expr) 66 { 67 if (expr == null) 68 return null; 69 70 var candidateExpr = expr.Parameters[0]; 71 var body = Expression.Not(expr.Body); 72 73 return Expression.Lambda<Func<T, bool>>(body, candidateExpr); 74 } 75 }
调用时
express= express.And(a => ids.Contains(id));
express= express.Or(a => ids.Contains(id));