/// <summary> /// 合并表达式 expr1 or expr2 /// 作者:李兴友 /// 日期:2020-06-08 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="expr1"></param> /// <param name="expr2"></param> /// <returns></returns> public static Expression <Func <T, bool> > Or <T>(this Expression <Func <T, bool> > expr1, Expression <Func <T, bool> > expr2) { ParameterExpression newParameter = Expression.Parameter(typeof(T), "c"); NewExpressionVisitor visitor = new NewExpressionVisitor(newParameter); var left = visitor.Replace(expr1.Body); var right = visitor.Replace(expr2.Body); var body = Expression.OrElse(left, right); return(Expression.Lambda <Func <T, bool> >(body, newParameter)); }
/// <summary> /// 合并表达式 expr1 AND expr2 /// 作者:李兴友 /// 日期:2020-06-08 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="expr1"></param> /// <param name="expr2"></param> /// <returns></returns> public static Expression <Func <T, bool> > And <T>(this Expression <Func <T, bool> > expr1, Expression <Func <T, bool> > expr2) { //return expression.lambda<func<t, bool>>(expression.andalso(expr1.body, expr2.body), expr1.parameters); ParameterExpression newParameter = Expression.Parameter(typeof(T), "c"); NewExpressionVisitor visitor = new NewExpressionVisitor(newParameter); var left = visitor.Replace(expr1.Body);// 重新生成了一个表达式目录树 var right = visitor.Replace(expr2.Body); var body = Expression.AndAlso(left, right); return(Expression.Lambda <Func <T, bool> >(body, newParameter)); }