摘要:Group 子句詳解
Group 子句怎麼分組,分組資料怎麼排序,讓我困惑了三天,終於稍為懂了,把心得寫下,不一定對唷!!
開始解釋囉!!
[ group o by o.Sex into g ] : 依照 o 物件的 Sex 屬性將 o 做分組後將分組結果存進(into) g 變數
MSDN 說:「 group 子句會傳回零個或多個 IGrouping<TKey, TElement> 物件序列 」
此時的 g 就是 IGrouping<TKey, TElement> 物件序列
(PS:IGrouping<TKey, TElement> 為有共同 Key 的物件集合)
依照 Sex 屬性理應分成兩組
記憶體中會變成
IGrouping<TKey, TElement> 物件序列
(1) = 代表下面記憶體
Key : M | new{Name="Max", Sex="M"} |
Key : M | new{Name="Ginger", Sex="M"} |
Key : M | new{Name="Dog", Sex="M"} |
Key : M | new{Name="Pig", Sex="M"} |
(2) = 代表下面記憶體
Key : F | new{Name="Apple", Sex="F"} |
Key : F | new{Name="Cat", Sex="F"} |
MSDN:「使用 into 時,您必須繼續進行查詢,最後再以 select 陳述式或其他 group 子句結束查詢」
select new { GroupKey = g.Key, obj = g } : 建立一個匿名型別回傳給 p 匿名型別區域變數
此時 p 會變成
GroupKey : M | obj = (1) |
GroupKey : F | obj = (2) |
(PS : (1)、(2) 代表之前所說的 IGrouping<TKey, TElement> 物件序列的記憶體)
有了以上的說明,相信 foreach 迴圈為什麼這樣跑,應該就可以了改吧。