1. 程式人生 > >語法之進化論之lambda表達式

語法之進化論之lambda表達式

方法 sta bbb 雜類 new clas turn lam 如果

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; } } }

轉至 楊中科教程

語法之進化論之lambda表達式