LINQ 中的分组运算符
这些运算符根据常见的共享属性将数据放入一些组中。
运算符 | 说明 | C# 查询表达式语法 | VB 查询表达式语法 |
---|---|---|---|
GroupBy | 按组组织项目序列,并将其作为类型为 IGrouping<key, element> 的 IEnumerable 集合返回 | group … by - 或 - 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
linq_query_operators.htm
广告