次の方法で共有


データのグループ化 (Visual Basic)

グループ化とは、各グループの要素が共通の属性を持つようにデータをグループに分ける操作を指します。

次の図は、文字のシーケンスをグループ化した結果を示しています。 各グループのキーは文字です。

LINQ グループ化操作を示す図。

データ要素をグループ化する標準クエリ演算子メソッドを次のセクションに示します。

メソッド

メソッド名 説明 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

こちらも参照ください