表达式树
转载 C#-表达式树 - 一只独行的猿 - 博客园 (cnblogs.com)
int[] ints1 = new int[] { 1,23,434,631,3,56,86,83 }; Console.WriteLine($"筛选前数据:{string.Join(',',ints1)}"); Expression<Func<int, bool>>[] expressions = new Expression<Func<int, bool>>[] { (b) => b > 3, (a) =>a > 5, (c) => c < 30 }; Expression<Func<int, bool>> expressionAnd = (i)=>true; expressions.ToList().ForEach(expr => { Console.WriteLine($"表达式:{expr.Body}"); //用于将参数名进行替换,二者参数不一样 ParameterExpression newParameter = Expression.Parameter(typeof(int), "c"); NewExpressionVisitor visitor = new NewExpressionVisitor(newParameter); //需要先将参数替换为一致的,可能参数名不一样 var left = visitor.Replace(expressionAnd.Body);//左侧的表达式 var right = visitor.Replace(expr.Body);//右侧的表达式 var body = Expression.AndAlso(left, right);//合并表达式 And--& AndAlso--&&(短路) //var body = Expression.OrElse(left, right);//合并表达式 And--| AndAlso--|| expressionAnd = Expression.Lambda<Func<int, bool>>(body, newParameter); }); Console.WriteLine($"合并后表达式:{expressionAnd.Body}"); int[] ints2 = ints1.Where(i=>expressionAnd.Compile().Invoke(i)).ToArray(); Console.WriteLine($"筛选后数据:{string.Join(',', ints2)}");
喜欢 C#、SQL、Web