Linq-grouping-operators
提供:Dev Guides
LINQでの演算子のグループ化
オペレーターは、共通の共有属性に基づいていくつかのグループにデータを入れます。
Operator | Description | C# Query Expression Syntax | VB Query Expression Syntax |
---|---|---|---|
GroupBy | Organize a sequence of items in groups and return them as an IEnumerable collection of type IGrouping<key, element> | group … by -or- group … by … into … | Group … By … Into … |
ToLookup | Execute a grouping operation in which a sequence of key pairs are returned | Not Applicable | Not Applicable |
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