自定义Lamda表达式作为筛选条件

时间:2022-08-30 20:00:24
var ints = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
            // var r = ints.Where(i => (i > 5 && i <= 7) || (i == 3)); // 要a实μ现?的?表í达?式?

            // 创′建¨参?数y i
            var parameter = Expression.Parameter(typeof(int), "i");

            // 创′建¨表í达?式? i > 5
            var con1 = Expression.Constant(5);
            var bin1 = Expression.GreaterThan(parameter, con1);

            // 创′建¨表í达?式? i < 7
            var con2 = Expression.Constant(7);
            var bin2 = Expression.LessThanOrEqual(parameter, con2);

            // 创′建¨表í达?式? i == 3
            var con3 = Expression.Constant(3);
            var bin3 = Expression.Equal(parameter, con3);

            // 组é合? i > 5 && i <= 7
            var body = Expression.And(bin1, bin2);

            // 组é合? ( i > 5 && i <= 7) OR (i == 3)
            body = Expression.Or(body, bin3);

            var lambda = Expression.Lambda<Func<int, bool>>(body, parameter);
            var _r = ints.Where(lambda.Compile());
FROM:http://www.rainsts.net/article.asp?id=535