C#中匿名委託以及Lambda運算式的執行個體詳解

來源:互聯網
上載者:User
一. C#從1.0到4.0, 隨著Linq,泛型的支援,代碼越來越簡單優雅

 1 int[] nums = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; 2             IEnumerable<int> newNums = from n in nums where n > 0 select n; 3             newNums = newNums.Where(new Func<int,int, bool>(delegate(int i,int index) { return i < index; })); 4             newNums = newNums.Where(new Func<int, int, bool>((int i, int index)=> i < index)); 5             newNums = newNums.Where(delegate(int i, int index) { return i < index; }); 6             newNums = newNums.Where((i, index) => i < index); 7             foreach (var i in newNums) 8             { 9                 Console.WriteLine(i);10             }

二.集合操作,也可適於到EF的資料庫操作

1.建立兩個實體類

 1     public class Store 2     { 3         public string Id; 4         public string Name; 5     } 6     public class Person 7     { 8         public string name { get; set; } 9         public int age { get; set; }10         public string StoreId { get; set; }11     }

2.插入資料

 1             var Stores = new List<Store>() 2             { 3                 new Store() { Id="1",Name="1班"}, 4                 new Store() { Id="2",Name="2班"} 5             }; 6  7             var Persons = new List<Person>() 8             { 9                 new Person() { name="p1",age=1, StoreId="1"},10                 new Person() { name="p2",age=2, StoreId="1"},11                 new Person() { name="p3",age=3, StoreId="1"},12                 new Person() { name="p4",age=4, StoreId="2"},13                 new Person() { name="p5",age=5, StoreId="1"},14                 new Person() { name="p6",age=6, StoreId="2"},15                 new Person() { name="p7",age=7, StoreId="1"},16                 new Person() { name="p8",age=8, StoreId="1"}17             };

3. 查詢年齡小於3歲的人1班和2班分別有幾個人

1             var plst = Persons.Where(o => o.age > 3).GroupBy(o => o.StoreId).Select(g => new { StoreId = g.Key, Count = g.Count() }).Join(Stores, s => s.StoreId, p => p.Id, (s, p) => new { s.StoreId, storeName = p.Name, s.Count });2             foreach (var p in plst)3             {4                 Console.WriteLine(p.storeName + "有" + p.Count + "個人");5             }

4.輸出

2班有2個人1班有3個人
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.