Share via


分組資料

分組指的是將資料分成群組,好讓每個群組中的項目都擁有共同屬性的作業。

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

LINQ 群組作業

下節會列出將資料項目分組的標準查詢運算子方法。

方法

方法名稱

描述

C# 查詢運算式語法

Visual Basic 查詢運算式語法

詳細資訊

GroupBy

將擁有共同屬性的項目分組。 每個群組都由一個 IGrouping<TKey, TElement> 物件代表。

group … by

-或-

group … by … into …

Group … By … Into …

Enumerable.GroupBy

Queryable.GroupBy

ToLookup

根據索引鍵選取器函式,將項目插入至 Lookup<TKey, TElement> (一對多字典)。

不適用。

不適用。

Enumerable.ToLookup

查詢運算式語法範例

下列程式碼範例在 C# 中使用 group by 子句或在 Visual Basic 中使用 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


            List<int> numbers = new List<int>() { 35, 44, 200, 84, 3987, 4, 199, 329, 446, 208 };

            IEnumerable<IGrouping<int, int>> query = from number in numbers
                                                     group number by number % 2;

            foreach (var group in query)
            {
                Console.WriteLine(group.Key == 0 ? "\nEven numbers:" : "\nOdd numbers:");
                foreach (int i in group)
                    Console.WriteLine(i);
            }

            /* This code produces the following output:

                Odd numbers:
                35
                3987
                199
                329

                Even numbers:
                44
                200
                84
                4
                446
                208
            */

請參閱

工作

HOW TO:建立巢狀群組 (C# 程式設計手冊)

HOW TO:依副檔名分組檔案 (LINQ)

HOW TO:分組查詢結果 (C# 程式設計手冊)

HOW TO:在分組作業上執行子查詢 (C# 程式設計手冊)

HOW TO:使用群組將檔案分割成許多檔案 (LINQ)

參考

group 子句 (C# 參考)

Group By 子句 (Visual Basic)

System.Linq

概念

標準查詢運算子概觀