C# Grouping
GroupBy collects items that share a key into groups. Each group holds a Key value and the items that produced that key.
Group by first letter
Each word groups under its first letter. OrderBy on the key prints the groups from a to c.
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
List<string> words = new List<string> { "apple", "ant", "banana", "bear", "cat" };
var groups = words.GroupBy(w => w[0]).OrderBy(g => g.Key);
foreach (var group in groups)
{
Console.WriteLine(group.Key + ": " + string.Join(", ", group));
}
}
}Group numbers by even or odd
The remainder after division by 2 is the key. Key 0 holds the even numbers and key 1 holds the odd numbers.
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6 };
var groups = numbers.GroupBy(n => n % 2).OrderBy(g => g.Key);
foreach (var group in groups)
{
string label = group.Key == 0 ? "Even" : "Odd";
Console.WriteLine(label + " (" + group.Count() + "): " + string.Join(", ", group));
}
}
}Group words by length
The length of each word is the key here. Words of the same length share one group.
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
List<string> words = new List<string> { "cat", "dog", "apple", "ant", "pear" };
var groups = words.GroupBy(w => w.Length).OrderBy(g => g.Key);
foreach (var group in groups)
{
Console.WriteLine(group.Key + ": " + string.Join(", ", group));
}
}
}Example
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
List<string> words = new List<string> { "dog", "deer", "cow", "cat", "duck" };
var groups = words.GroupBy(w => w[0]).OrderBy(g => g.Key);
foreach (var group in groups)
{
Console.WriteLine(group.Key + ": " + string.Join(", ", group));
}
}
}Key points
- GroupBy takes a lambda that returns the key for each item.
- Each group is a sequence of its own items.
- Items inside a group keep their source order.
- OrderBy on the group key pins the group print order.
- string.Join builds one line from all items in a group.
- Count on a group counts the items inside that group.
In this example, GroupBy collects each word under its first letter. OrderBy sorts the groups by that letter. Each line joins the words of one group with commas.
Note
Group order is pinned in these exhibits with OrderBy(g => g.Key).
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Why do these exhibits sort the groups with OrderBy(g => g.Key)?