对数据进行分组 (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  

请参阅