[C#.Net&Linq]LINQ to Object 學習筆記(資料群組GroupBy、ToLookup、ToDictionary)
範例資料表[Authors]
1: //===GroupBy===
2: //IEnumerable<IGrouping<TKey,TElement>>列舉型別
3: IEnumerable<IGrouping<string,Authors>> contacts = from author in Authors
4: group author by author.State;
5: //GroupBy轉換後,儲存在IGrouping型態物件中
6: //IGrouping<TKey,TElement>
7: foreach(IGrouping<string,Authors> item in contacts)
8: {
9: Console.WriteLine(item.Key);
10: Console.WriteLine(item);
11: }
12: //使用匿名型別
13: var contact = Authors.GroupBy(author=>author.State);
14: foreach(var item in contact)
15: {
16: Console.WriteLine(item.Key);
17: Console.WriteLine(item);
18: }
19:
20:
21: //===ToLookup===
22: //集合物件Authors的ToLookup方法,產生泛型版本的ILookup
23: ILookup<string,Authors> contacts = Authors.ToLookup(author=>author.State);
24: //與GroupBy一樣ToLookup轉換後,儲存在IGrouping型態物件中
25: //IGrouping<TKey,TElement>
26: foreach(IGrouping<string,Authors> items in contacts)
27: {
28: Console.WriteLine(items.Key);
29: Console.WriteLine(items);
30: }
31: //使用匿名型別
32: var contact = Authors.ToLookup(author=>author.State);
33: foreach(var items in contact)
34: {
35: Console.WriteLine(items.Key);
36: Console.WriteLine(items);
37: }
結果:
1: //===ToDictionary===
2: Dictionary<string, Authors> contacts = Authors.ToDictionary(author=>author.Au_id);
3: foreach(KeyValuePair<string, Authors> item in contacts)
4: {
5: Console.WriteLine(item.Key);
6: Console.WriteLine(item.Value);
7: }
8: //使用匿名型別
9: var contacts = Authors.ToDictionary(author=>author.Au_id);
10: foreach(var item in contacts)
11: {
12: Console.WriteLine(item.Key);
13: Console.WriteLine(item.Value);
14: }
結果: