using System;using System.Collections.Generic;using System.Linq;namespace ConsoleApplication1d{class CTX { public int id = 10; public string name = "rich"; public int age = 28; public CTX(int id) { this.id = id; } } class Test { delegate List EvenCheck(List lst); public static void Main() { List lst = new List () { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; //List初始化器 Dictionarydict = new Dictionary ()//Dictionary初始化器 { { 1, new CTX(20) {name = "Tom" } },//对象的初始化器 { 2, new CTX(0) {age = 30, id = 10020, name = "unknown" } //对象的初始化器 } }; //Func 系统定义的委托,参数数目可变, 至少二个参数,最后一个为返回值类型,其余为输入参数类型 Func fdg = p => p + 10; Console.WriteLine(fdg(333));//343 Func fadg = (p, q) => (p + q).ToString(); Console.WriteLine(fadg(-10, -20));//-30 EvenCheck eck = p => //委托中的lambda,相当于一个匿名函数,参数为p, 返回值为list ,符合EvenCheck的委托类型,因此可直接赋值 { List tlst = new List (); foreach(var e in p) { if (e % 2 == 0) tlst.Add(e); } return tlst; }; List lst2 = lst.Where(p => p % 2 == 0).ToList(); //条件表达式中的lambda,Where参数为Func ,因此可用lambda List lst3 = eck(lst); int lx = lst3.SingleOrDefault(p => p == 6); //条件表达式中的lambda lst3 = lst3.OrderBy(p => p).ToList(); //升序,OrderBy参数为Func ,因此可用lambda lst3 = lst3.OrderByDescending(p => p).ToList();//降序,OrderByDescending参数为Func ,因此可用lambda lst3.Sort();//升序 foreach(var l in lst3) { Console.Write(l +" "); } Console.WriteLine(); } }}