码迷,mamicode.com
首页 > 其他好文 > 详细

Expression 生成 Lambda

时间:2017-10-19 09:24:32      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:amd   lin   and   exp   匿名   nts   express   code   ring   

public static event Func<Student, bool> myevent;
        public delegate void del(int i, int j);
        static void Main(string[] args)
        {
            
            var students = new List<Student> { 
              new Student(){ Id=3, Age=20, Name="张三1", Sex=true   , GradeId=1},
              new Student(){ Id=1, Age=22, Name="李四1", Sex= false , GradeId=2},
              new Student(){ Id=4, Age=13, Name="王二", Sex= false , GradeId=1},
              new Student(){ Id=2, Age=11, Name="赵六", Sex=true   , GradeId=2},
            
            };

            // BookShopPlus2Entities db = new BookShopPlus2Entities();
            //AsNoTracking查询的对象不要放在对象池中
            //特别说明:对于使用AsNoTracking()的数据不能用于修改。
            //List<Book> db = bsc.Books.AsNoTracking().ToList();

            //del mydel = new del(add);
            //mydel.Invoke(1, 9);
            //// //匿名方法
            //mydel += delegate(int h, int m)
            //{

            //};
            ////Lamda表达式
            //mydel += (a, b) =>
            //{
            //    Console.WriteLine(a + b);
            //};

            //生成 1==1
            Expression expwhere = Expression.Equal(Expression.Constant(1), Expression.Constant(1));
            //生成 s=>
            ParameterExpression exps = Expression.Parameter(typeof(Student), "s");
            //生成s.Age>12
            Expression exp1 = Expression.GreaterThan(Expression.Property(exps, "Age"), Expression.Constant(12));
            //生成s.Age<22
            Expression exp2 = Expression.LessThan(Expression.Property(exps, "Age"), Expression.Constant(22));
            //生成 s.Age>12 and  s.Age<22  或连接 Expression.Or  and 连接   Expression.And
            Expression exp3 = Expression.And(exp1, exp2);     
            //Expression<Func<Student, bool>> lamband = Expression.Lambda < Func<Student, bool>.Combine();
            //生成s=>Age>12 AND    s.Age<22
            Expression<Func<Student, bool>> lamband =
            Expression.Lambda<Func<Student, bool>>(exp3, exps);
            var s = students.Where(lamband.Compile()).ToList();
        }

        
    }
    public class Student
    {
        public int Id { get; set; } //学号
        public string Name { get; set; } //学员姓名
        public int Age { get; set; } //学生年龄
        public bool Sex { get; set; } //学生性别
        public int GradeId { get; set; }
    }

 

Expression 生成 Lambda

标签:amd   lin   and   exp   匿名   nts   express   code   ring   

原文地址:http://www.cnblogs.com/wlzhang/p/7690630.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!