.NET技术-6.0. Expression 表达式树 生成 Lambda public static event FuncStudent, bool myevent; public delegate void del( int i, int j); static void Main( string [] args) { var students = new ListStudent { new Student(){ Id= 3 , Age= 2
.NET技术-6.0. 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; } }
引用:https://www.cnblogs.com/wlzhang/p/7690630.html