Expression 生成 Lambda

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Expression 生成 Lambda相关的知识,希望对你有一定的参考价值。

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的主要内容,如果未能解决你的问题,请参考以下文章

Java Lambda

Expression.Call 在简单的 lambda 表达式中。可能吗?

python: lambda、yield-statement/expression 和循环(澄清)

Expression.Compile 与 Lambda、直接与虚拟调用的性能

java Lambda expression

Lamda Expression