Lambda表达式
定义:
"Lambda表达式"是一个匿名函数,是一种高效的类似于函数式编程的表达式,Lambda简化了开发中需要编写的代码量。它可以包含表达式和语句,并且可用于创建委托或表达式目录树类型,支持带有可绑定到委托或表达式树的输入参数的内联表达式。所有Lambda表达式都使用Lambda运算符=>,该运算符读作"goes to"。Lambda运算符的左边是输入参数(如果有),右边是表达式或语句块。Lambda表达式x => x * x读作"x goes to x times x"。
Lambda表达式在一定程度上就是匿名方法的另一种表现形式。
- (参数列表)=>表达式或语句块
Lambda表达式可以有多个参数、一个参数,或者没有参数。其参数类型可以隐式或者显式。//创建一个Student类 public class Student { public int grade { get; set; } //设置属性 public int id { get; set; } //设置属性 public Student(int id,int grade ) //设置属性(构造函数构造) { this. id = id ; //初始化属性值int this. grade = grade ; //初始化属性值grade } } //使用List进行泛型编程,创建一个对象的集合 List<Student> student = new List<Student>(); //创建泛型对象 Student s1 = new Student(3403,"89"); //创建一个对象 Student s2 = new Student(3404, "76"); //创建一个对象 Student s3 = new Student(3405, "86"); //创建一个对象 Student s4 = new Student(3406, "65"); //创建一个对象 student.Add (s1); //添加一个对象 student.Add (s2); //添加一个对象 student.Add (s3); //添加一个对象 student.Add (s4); //添加一个对象 //匿名方法 (通过使用IEnumerable接口创建了一个result集合,并且该集合中填充的是成绩大于80的Student对象。) IEnumerable<Student> result = student.Select (delegate(Student s) { return s.grade > 80; }); IEnumerable<Student> result = student.Select(Student => Student.grade > 80); //上述代码同样返回了一个Student对象的集合给变量result
(x, y) => x * y //多参数,隐式类型=> 表达式
x => x * 5 //单参数, 隐式类型=>表达式
x => { return x * 5; } //单参数,隐式类型=>语句块
(int x) => x * 5 //单参数,显式类型=>表达式
(int x) => { return x * 5; } //单参数,显式类型=>语句块
() => Console.WriteLine() //无参数