LINQ分組操作


運算子將資料基於一個共同的共用屬性放入一些分組

操作 描述 C#查詢表示式語法 VB查詢表示式語法
GroupBy 組織專案的順序組,並將其返回IEnumerable型別的集合IGrouping<key, element> group … by -or- group … by … into … Group … By … Into …
ToLookup 執行在其中的金鑰對的序列被返回分組運算 不適用 不適用

GroupBy範例- 查詢表示式

C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Operators
{
  class Program
  {
     static void Main(string[] args)
     {
        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);
        }
              Console.ReadLine();                
     }
  }
}

VB

Module Module1
  Sub Main()
     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
     
     For Each group In query
        Console.WriteLine(If(group.Remainder = 0, vbCrLf &"Even numbers:", vbCrLf &"Odd numbers:"))
        For Each num In group.Group           
           Console.WriteLine(num)
        Next 
     Next 
           Console.ReadLine()
  End Sub
End Module

當在C#或VB上面的程式碼被編譯和執行時,它產生了以下結果:

Odd numbers: 
35 
3987 
199 
329 

Even numbers: 
44 
200 
84 
4 
446 
208