Linq數據分組全面描述
Linq有很多值得學習的地方,這里我們主要介紹Linq數據分組,包括介紹使用 Group 關鍵字等方面。
Linq數據分組(GROUP BY)
根據元素的一個或多個字段對查詢結果中的元素進行分組。例如:按年級 (class year) 對學生進行Linq數據分組:
- Dim studentsByYear = From student In students _
- Select student _
- Group By year = student.Year _
- Into Classes = Group
輸出結果的程序:
- For Each yearGroup In studentsByYear
- Console.WriteLine(vbCrLf & "Year: " & yearGroup.year)
- For Each student In yearGroup.Classes
- Console.WriteLine(" " & student.Last & ", " & student.First)
- Next
- Next
完整語法:
- Group [ listField1 [, listField2 [...] ] By keyExp1 [, keyExp2 [...] ]
- Into aggregateList
◆listField1, listField2 :可選。查詢變量的一個或多個字段,這些查詢變量顯式標識要包括在分組結果中的字段。如果未指定任何字段,則查詢變量的所有字段都包括在分組結果中。
◆keyExp1 :必需。一個表達式,標識用于確定元素的分組的鍵。可以指定多個鍵來指定一個組合鍵。
◆keyExp2 :可選。一個或多個附加鍵,與 keyExp1 組合在一起,創建一個組合鍵。
◆aggregateList :必需。一個或多個表達式,標識如何對組進行聚合。若要為分組結果標識一個成員名稱,請使用 Group 關鍵字,該關鍵字可以:Into Group
Linq數據分組例如:
- Dim ***層_分組 = From cust In db.Customers _
- Group By 國家 = cust.Country _
- Into 第二層_分組元素 = Group, Count() _
- Order By 國家
- For Each A分組 In ***層_分組
- Console.WriteLine(A分組.國家 & "(" & A分組.Count & ")")
- For Each A元素 In A分組.第二層_分組元素
- Console.WriteLine(vbTab + A元素.CompanyName + "," + A元素.ContactName)
- Next
- Next
【編輯推薦】