位置:首頁 > 其他技術 > LinQ教學 > LINQ分組操作

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