- 理论部分相信大家都看过,表示不是很理解。
- 俺也一样
- 因为缺乏实操
- 理性认知的过程往往是 实践-认知-实践 的反复轮询
- 没有废话,直接实操,看注释
using System;
using System.Linq;
using System.Linq.Expressions;
var arr = new int[] { 1, 2, 5, 6, 7, 8 };
var p = Expression.Parameter(typeof(int), "x"); //x=>
var eight = Expression.Constant(8, typeof(int));//8
var xLessThanEight = Expression.LessThan(p, eight);//x<8
var one = Expression.Constant(1, typeof(int));//1
var xGreaterThanOne = Expression.GreaterThan(p, one);//x>1
var and = Expression.AndAlso(xLessThanEight, xGreaterThanOne);//x<8 && x>1
Expression<Func<int, bool>> lambda =
Expression.Lambda<Func<int, bool>>(
and,
new ParameterExpression[] { p });
var func = lambda.Compile();//x => x < 8 && x > 1
var result = arr.Where(func).ToArray();
var result2 = arr.Where(x => x < 8 && x > 1).ToArray();
System.Console.WriteLine(string.Join(',', result));//2,5,6,7
System.Console.WriteLine(string.Join(',', result2));//2,5,6,7