语法之进化论之lambda表达式
namespace 匿名函数 { /// <summary> /// 语法之进化论 /// </summary> class Program { delegate bool MetherdDeleget(string pStr); static void Main(string[] args) { //m指向匿名函数 delegate(参数列表) {方法体 }; MetherdDeleget m = delegate(string s) { Console.WriteLine(s); return false; }; m("匿名函数"); //lambda MetherdDeleget m1 = (s) => { Console.WriteLine(s); return false; }; m("lambda"); //进一步1: MetherdDeleget m2 = (s) => { return s=="tom"; }; Console.WriteLine(m2("tom")); //当方法体只有一句话,且有返回值时,写法上可以进一步简化: //甚至如果只有一个参数的话() 也不必写 MetherdDeleget m3 = (s) => s == "tom"; Console.WriteLine(m3("tom")); //////////list的复杂类型排序/////////////////// List<Person> plist = new List<Person>(); plist.Add(new Person() { Name = "tom", Age = 20 }); plist.Add(new Person() { Name = "jim", Age = 25 }); plist.Add(new Person() { Name = "aaa", Age = 10 }); plist.Add(new Person() { Name = "bbb", Age = 35 }); plist.Add(new Person() { Name = "ccc", Age = 50 }); plist.Add(new Person() { Name = "ddd", Age = 15 }); foreach(Person eachp in plist.OrderBy(p=>p.Age)) { Console.WriteLine("名字:{0} 年龄:{1}",eachp.Name,eachp.Age); } foreach (Person eachp in plist.OrderByDescending(p => p.Age)) { Console.WriteLine("名字:{0} 年龄:{1}", eachp.Name, eachp.Age); } Console.ReadKey(); } } class Person { public string Name { set; get; } public int Age { set; get; } } }
转至 杨中科教程