Linq數(shù)據(jù)分組全面描述
Linq有很多值得學(xué)習(xí)的地方,這里我們主要介紹Linq數(shù)據(jù)分組,包括介紹使用 Group 關(guān)鍵字等方面。
Linq數(shù)據(jù)分組(GROUP BY)
根據(jù)元素的一個(gè)或多個(gè)字段對(duì)查詢結(jié)果中的元素進(jìn)行分組。例如:按年級(jí) (class year) 對(duì)學(xué)生進(jìn)行Linq數(shù)據(jù)分組:
- Dim studentsByYear = From student In students _
- Select student _
- Group By year = student.Year _
- Into Classes = Group
輸出結(jié)果的程序:
- 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 :可選。查詢變量的一個(gè)或多個(gè)字段,這些查詢變量顯式標(biāo)識(shí)要包括在分組結(jié)果中的字段。如果未指定任何字段,則查詢變量的所有字段都包括在分組結(jié)果中。
◆keyExp1 :必需。一個(gè)表達(dá)式,標(biāo)識(shí)用于確定元素的分組的鍵??梢灾付ǘ鄠€(gè)鍵來指定一個(gè)組合鍵。
◆keyExp2 :可選。一個(gè)或多個(gè)附加鍵,與 keyExp1 組合在一起,創(chuàng)建一個(gè)組合鍵。
◆aggregateList :必需。一個(gè)或多個(gè)表達(dá)式,標(biāo)識(shí)如何對(duì)組進(jìn)行聚合。若要為分組結(jié)果標(biāo)識(shí)一個(gè)成員名稱,請(qǐng)使用 Group 關(guān)鍵字,該關(guān)鍵字可以:Into Group
Linq數(shù)據(jù)分組例如:
- 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
【編輯推薦】