分組指的是將資料放在群組中,好讓每一個群組中的項目共用共同的屬性。
下圖顯示一系列字元的分組結果。 每個群組的索引鍵是字元。
將數據元素分組的標準查詢運算符方法列在下一節中。
方法
| 方法名稱 | 說明 | Visual Basic 查詢表達式語法 | 詳細資訊 |
|---|---|---|---|
| 按組分組 | 共用共同屬性的群組項目。 每個群組都會以 IGrouping<TKey,TElement> 物件表示。 | Group … By … Into … |
Enumerable.GroupBy Queryable.GroupBy |
| ToLookup | 根據索引鍵選取器函式,將元素插入 Lookup<TKey,TElement> (一對多字典)。 | 不適用。 | Enumerable.ToLookup |
查詢運算式語法範例
下列程式代碼範例會根據子句是否為偶數或奇數,使用 Group By 子句將清單中的整數分組。
Dim numbers As New System.Collections.Generic.List(Of Integer)(
New Integer() {35, 44, 200, 84, 3987, 4, 199, 329, 446, 208})
Dim query = From number In numbers
Group By Remainder = (number Mod 2) Into Group
Dim sb As New System.Text.StringBuilder()
For Each group In query
sb.AppendLine(If(group.Remainder = 0, vbCrLf & "Even numbers:", vbCrLf & "Odd numbers:"))
For Each num In group.Group
sb.AppendLine(num)
Next
Next
' Display the results.
MsgBox(sb.ToString())
' This code produces the following output:
' Odd numbers:
' 35
' 3987
' 199
' 329
' Even numbers:
' 44
' 200
' 84
' 4
' 446
' 208