[C#.Net&Linq]LINQ to Object 學習筆記(資料群組[GroupBy-IGrouping<TKey,TElement>])
[GroupBy-IGrouping<TKey,TElement>]
1: //建立資料來源
2: string[] weekDayList = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" };
3: //群組
4: Console.WriteLine("===依第一個字母進行群組===");
5: //寫法一: from...in...group...by 使用具名型別 IEnumerable<IGrouping<string, string>>
6: Console.WriteLine("***寫法一***");
7: IEnumerable<IGrouping<string, string>> groupQuery1 = from q in weekDayList
8: group q by q.Substring(0, 1);
9: foreach (var items in groupQuery1)
10: {
11: Console.WriteLine(string.Format("群組字母:{0}", items.Key));
12: foreach (var item in items)
13: {
14: Console.WriteLine(item);
15: }
16: }
17: //寫法二: from...in...group...by 使用匿名型別 var
18: Console.WriteLine("***寫法二***");
19: var groupQuery2 = from q in weekDayList
20: group q by q.Substring(0, 1);
21: foreach (var items in groupQuery2)
22: {
23: Console.WriteLine(string.Format("群組字母:{0}", items.Key));
24: foreach (var item in items)
25: {
26: Console.WriteLine(item);
27: }
28: }
29:
30: //寫法三:直接使用集合物件的方法GroupBy
31: Console.WriteLine("***寫法三***");
32: var groupQuery3 = weekDayList.GroupBy(q => q.Substring(0, 1));
33: foreach (var items in groupQuery3)
34: {
35: Console.WriteLine(string.Format("群組字母:{0}", items.Key));
36: foreach (var item in items)
37: {
38: Console.WriteLine(item);
39: }
40: }
輸出結果: