將資料分組 (Visual Basic)

分組指的是將資料放在群組中,好讓每一個群組中的項目共用共同的屬性。

下圖顯示一系列字元的分組結果。 每個群組的索引鍵是字元。

Diagram that shows a LINQ Grouping operation.

分組資料項目的標準查詢運算子方法詳列於下一節。

方法

方法名稱 描述 Visual Basic 查詢運算式語法 相關資訊
GroupBy 共用共同屬性的群組項目。 每個群組都由一個 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  

另請參閱