LINQ 中的分组运算符

运算符根据通用的共享属性将数据放入某些组中。

运算符 描述 C# 查询表达式语法 VB 查询表达式语法
GroupBy 将一系列项目组织成组并将它们作为 IGrouping<key, element> 类型的 IEnumerable 集合返回 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 ? "
Even numbers:" : "
Odd 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

linq_query_operators.html