Overview
A group operation puts data into groups such that the elements in each group share a common attribute.
methods
Method | Description | Query expression |
---|---|---|
GroupBy | Groups elements that share a common attribute. Groups are represented by an IGrouping<TKey,TElement> . | group … by |
ToLookup | Inserts elements into a Lookup<TKey, TElement> via a key-selector function. A Lookup is a one-to-many dictionary. | N/A |
GroupBy
Example
Group integers into a list based on whether they are even or odd:
List<int> numbers = [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);
}
}
In method syntax:
List<int> numbers = [35, 44, 200, 84, 3987, 4, 199, 329, 446, 208];
IEnumerable<IGrouping<int, int>> query = numbers.GroupBy(number => number % 2);
foreach (var group in query)
{
Console.WriteLine(group.Key == 0 ? "\nEven numbers:" : "\nOdd numbers:");
foreach (int i in group)
{
Console.WriteLine(i);
}
}
more examples
Data can be grouped by:
- A single property
- The first letter of a string property
- A computed numeric range
- Boolean predicate or other expression
- A compound key