group by
Learn group by and into in query syntax.
Grouping with group by
group ... by partitions elements into groups by a key. The result is a sequence of IGrouping<TKey, TElement>, each holding the elements that share a key. Example: from n in numbers group n by n % 2.
This splits the numbers into two groups: even and odd. Each group's Key property is the key (0 or 1); the group itself is the sequence of elements with that key. You can iterate the groups with foreach.
Continuation with into
into lets you continue the query after grouping. After group n by n % 2 into g, g becomes a range variable usable in the following clauses.
In the continuation you can process each group: select new { Key = g.Key, Count = g.Count() }. This produces a sequence of anonymous objects holding each group's key and count. into is handy for post-group projection.
Exercise Count even/odd groups
Group the numbers array by even/odd with group n by n % 2 into g. For each group produce an anonymous type with select new { Key = g.Key, Count = g.Count() }. Iterate with foreach and print each group's Key and Count with Console.WriteLine($"{g.Key}: {g.Count}").
Show example solution
{g.Count}"); }.
Example solution:
using System;
using System.Linq;
class Program
{
static void Main()
{
int[] numbers = { 1, 2, 3, 4, 5, 6 };
var query = from n in numbers
group n by n % 2 into g
select new { Key = g.Key, Count = g.Count() };
foreach (var g in query)
{
Console.WriteLine($"{g.Key}: {g.Count}");
}
}
}
Test yourself
-
Complete the group by clause
var query = from n in numbers ____ n by n % 2;Show answer
var query = from n in numbers group n by n % 2; -
What type does group by produce?
- A number
- An array
- A set of IGrouping<TKey, TElement>
- A string
Show answer
A set of IGrouping<TKey, TElement> — Correct. group by produces a set of IGrouping<TKey, TElement>.
-
Match keyword to its role
- group
- Clusters elements
- by
- Specifies the key
- into
- Creates a continuation
- select
- Projects