代码改变世界

C# Lambda 表达式学习之(三):动态构建类似于 c => c.Age == null || c.Age > 18 的表达式

2019-03-20 19:13  音乐让我说  阅读(366)  评论(0编辑  收藏  举报

可能你还感兴趣:

1. C# Lambda 表达式学习之(一):得到一个类的字段(Field)或属性(Property)名,强类型得到

2. C# Lambda 表达式学习之(二):LambdaExpression 实战练习

3. 基于 Entity Framework FluentAPI 思想的强类型的 Lambda Expressions 实体映射

4. C# Lambda 表达式学习之(四):动态构建类似于 c => c.Age == 2 || c.Age == 5 || c => c.Age == 17 等等一个或多个 OrElse 的表达式

 

 直接贴代码了:

    class User
    {
        public int Id { get; set; }
        public int? Age { get; set; }
    }

 

Program

    class Program
    {
        static void Main(string[] args)
        {
            List<User> userList = new List<User>()
            {
                new User(){ Id = 1, Age = 19 },
                new User(){ Id = 2, Age = 15 },
                new User(){ Id = 3, Age = null },
                new User(){ Id = 4, Age = 23 },
                new User(){ Id = 5, Age = null },
            };
            var resultExp = BuildIsNullOrGreaterThanOrEqualExpression<User>("Age", 18);
            IEnumerable<User> queryResult = userList.Where(resultExp.Compile());
            Console.WriteLine("下面是年龄没有填写,或者填写的年龄大于 18 岁的用户如下:\n");
            foreach (var item in queryResult)
            {
                Console.WriteLine("用户ID:" + item.Id + ",年龄:" + item.Age);
            }
            Console.WriteLine("ok");
        }

        public static Expression<Func<T, bool>> BuildIsNullOrGreaterThanOrEqualExpression<T>(string propName, object propValue)
        {
            var exp = Expression.Parameter(typeof(T), "t");
            Expression propExp = Expression.PropertyOrField(exp, propName);
            var propType = ((MemberExpression)propExp).Type;
            var constant1Exp = Expression.Constant(null, propType);
            var constant2Exp = Expression.Constant(propValue, propType);
            var left = Expression.Equal(propExp, constant1Exp);
            var right = Expression.GreaterThanOrEqual(propExp, constant2Exp);
            Expression body = Expression.OrElse(left, right);
            return Expression.Lambda<Func<T, bool>>(body, exp);
        }
    }

 

 运行截图:

 

谢谢浏览!