Lambda 表达式
C#的Lambda 表达式都使用 Lambda 运算符 =>,该运算符读为“goes to”。语法如下:
形参列表=>函数体
函数体多于一条语句的可用大括号括起。
lambda表达式:
1.一个参数:param=>expr
2.多个参数:(param-list)=>expr
示例
委托
delegate int AddHandler(int x, int y); public static int Print(int x,int y) { return x + y; }
static void Main(string[] args)
{
AddHandler add = Print;
Console.WriteLine(add(1,2));//打印3,委托方法
Console.ReadLine();
}
Lambda 表达式
delegate int AddHandler(int x, int y); static void Main(string[] args) { AddHandler add = (x,y)=>x+y; Console.WriteLine(add(1, 2));//打印3,lambda表达式 Console.ReadLine(); }
示例:根据国籍分组
IEnumerable<IGrouping<string, Person>> query = getPersonList.GroupBy(pet => pet.CountryName); foreach (IGrouping<string, Person> info in query){ List<Person> sl = info.ToList<Person>();//分组后的集合 foreach (Person per in sl){ } }
示例
List<Person> persons = PersonList(); persons = persons.Where(p => p.Age > 6).ToList();//所有age>6的集合 Console.WriteLine("所有Age>6的集合:"); foreach (Person p in persons) { Console.WriteLine("\t{0}:\t{1}", p.Name,p.Age); } /* 执行后的结果: 所有Age>6的集合: 0儿子: 8 1儿子: 7 */ /* Person per = persons.SingleOrDefault(p => p.Age == 1);//age=1的儿子 Console.WriteLine(per.Name+":"+ per.Age); 执行之后的结果: 7儿子:1 */ persons = persons.Where(p=>p.Name.Contains("儿子")).ToList();//所有name 包含儿子的集合 Console.WriteLine("符合条件的个数:"+persons.Count); foreach (Person p in persons) { Console.WriteLine("\t{0}:\t{1}", p.Name, p.Age); } Console.ReadLine();
Func<T>委托
//Func<T>委托 delegate int AddHandler(int x); delegate int AddHandler2(int x,int y); static void Main(string[] args) { Func<int, string> add = p => p + 10 + "--返回类型为string"; Console.WriteLine(add(10));//20--返回类型为string Func<int, int, bool> add2 = (x, y) => { if (x + y >= 10) { return true; } else { return false; } }; Console.WriteLine(add2(1,2));//False Console.WriteLine(add2(5, 5));//True Console.ReadLine(); }
两段代码可以看出,Func<T>多参数前面是委托的参数类型,最后是委托返回的类型