ZetCode

C# LINQ group by

last modified November 6, 2026

In this article we show how to group data in C# with LINQ queries.

Language-Integrated Query (LINQ) is a set of query features built into C#. It works with arrays, lists, XML documents, databases, and other data sources through a common syntax.

A group by operation divides elements into groups that share a common key. The key can be a property, a computed value, a combination of several properties, or the result of a condition. Each group is an IGrouping<TKey, TElement>: a sequence of elements with a Key property.

In the query syntax, group specifies the element to put into the groups, by specifies the key, and into names the groups so that they can be filtered, sorted, or projected. The method syntax uses the GroupBy method. The groups come in the order in which their keys first appear in the source, and the elements in each group keep their original order.

Group by a key

In the first example, we group cars by their colour.

Program.cs
List<Car> cars =
[
    new ("Audi", "red", 52642),
    new ("Mercedes", "blue", 57127),
    new ("Skoda", "black", 9000),
    new ("Volvo", "red", 29000),
    new ("Bentley", "yellow", 350000),
    new ("Citroen", "white", 21000),
    new ("Hummer", "black", 41400),
    new ("Volkswagen", "white", 21600),
];

var groups = from car in cars
             group car by car.Colour;

foreach (var group in groups)
{
    Console.WriteLine(group.Key);

    foreach (var car in group)
    {
        Console.WriteLine($" {car.Name} {car.Price}");
    }
}

record Car(string Name, string Colour, int Price);

The query returns a sequence of groups.

var groups = from car in cars
             group car by car.Colour;

The group car by car.Colour clause puts each car into the group for its colour.

foreach (var group in groups)
{
    Console.WriteLine(group.Key);

    foreach (var car in group)

The outer loop goes over the groups and prints their keys; the inner loop goes over the cars of each group.

$ dotnet run
red
 Audi 52642
 Volvo 29000
blue
 Mercedes 57127
black
 Skoda 9000
 Hummer 41400
yellow
 Bentley 350000
white
 Citroen 21000
 Volkswagen 21600

The GroupBy method

The GroupBy method is the method-syntax equivalent of group by. Its overloads can also transform the elements and the resulting groups.

Program.cs
List<string> words =
[
    "war", "water", "cup", "cloud", "atom", "abyss", "soup", "book",
    "moon", "nice", "sky", "forest"
];

var groups = words.GroupBy(w => w.Length);

foreach (var group in groups)
{
    Console.WriteLine($"{group.Key}: {string.Join(", ", group)}");
}

Console.WriteLine();

var res = words.GroupBy(
    w => w[0],
    w => w.ToUpper(),
    (letter, items) => $"{letter} ({items.Count()}): {string.Join(" ", items)}");

foreach (var line in res)
{
    Console.WriteLine(line);
}

The words are grouped by their length.

var groups = words.GroupBy(w => w.Length);

The key selector is the only required argument.

var res = words.GroupBy(
    w => w[0],
    w => w.ToUpper(),
    (letter, items) => $"{letter} ({items.Count()}): {string.Join(" ", items)}");

This overload takes a key selector, an element selector, and a result selector. The words are grouped by their first letter, each word is converted to uppercase, and each group is turned into a single string.

$ dotnet run
3: war, cup, sky
5: water, cloud, abyss
4: atom, soup, book, moon, nice
6: forest

w (2): WAR WATER
c (2): CUP CLOUD
a (2): ATOM ABYSS
s (2): SOUP SKY
b (1): BOOK
m (1): MOON
n (1): NICE
f (1): FOREST

Group and aggregate

A common task is to compute a value for each group, such as a sum or an average.

Program.cs
Revenue[] revenues =
[
    new (1, "Q1", 2340),
    new (2, "Q1", 1200),
    new (3, "Q1", 980),
    new (4, "Q2", 340),
    new (5, "Q2", 780),
    new (6, "Q3", 2010),
    new (7, "Q3", 3370),
    new (8, "Q4", 540),
];

var res = from revenue in revenues
          group revenue by revenue.Quarter
          into g
          select new { Quarter = g.Key, Total = g.Sum(e => e.Amount) };

foreach (var line in res)
{
    Console.WriteLine(line);
}

record Revenue(int Id, string Quarter, int Amount);

We have revenues for four quarters. We group them by quarter and sum the amounts.

var res = from revenue in revenues
          group revenue by revenue.Quarter
          into g
          select new { Quarter = g.Key, Total = g.Sum(e => e.Amount) };

The into g clause continues the query with the groups. For each group, we create an anonymous object with the quarter and the total.

$ dotnet run
{ Quarter = Q1, Total = 4520 }
{ Quarter = Q2, Total = 1120 }
{ Quarter = Q3, Total = 5380 }
{ Quarter = Q4, Total = 540 }

Filter groups

A where clause after into filters the groups, similar to HAVING in SQL.

Program.cs
Revenue[] revenues =
[
    new (1, "Q1", 2340),
    new (2, "Q1", 1200),
    new (3, "Q1", 980),
    new (4, "Q2", 340),
    new (5, "Q2", 780),
    new (6, "Q3", 2010),
    new (7, "Q3", 3370),
    new (8, "Q4", 540),
];

var res = from revenue in revenues
          group revenue by revenue.Quarter
          into g
          where g.Count() == 2
          select new { Quarter = g.Key, Total = g.Sum(c => c.Amount) };

foreach (var line in res)
{
    Console.WriteLine(line);
}

record Revenue(int Id, string Quarter, int Amount);

Only quarters with exactly two revenues pass the filter.

where g.Count() == 2

The condition is applied to each group, not to the individual revenues.

$ dotnet run
{ Quarter = Q2, Total = 1120 }
{ Quarter = Q3, Total = 5380 }

Group by a composite key

To group by several properties, we use an anonymous type as the key.

Program.cs
User[] users =
[
    new ("John", "Doe", "gardener"),
    new ("Jane", "Doe", "teacher"),
    new ("Roger", "Roe", "driver"),
    new ("Peter", "Doe", "teacher"),
    new ("Pavol", "Novak", "programmer"),
    new ("Albert", "Novak", "teacher"),
    new ("Sam", "Novak", "driver"),
    new ("Peter", "Horvath", "accountant"),
    new ("Lucia", "Horvath", "accountant"),
    new ("Michael", "Novak", "programmer"),
];

var groups = from user in users
             group user by new { user.LastName, user.Occupation };

foreach (var group in groups)
{
    Console.WriteLine(group.Key);

    foreach (var e in group)
    {
        Console.WriteLine($"{e}");
    }

    Console.WriteLine("----------------");
}

record User(string FirstName, string LastName, string Occupation);

The users are grouped by both their last name and occupation.

group user by new { user.LastName, user.Occupation };

Anonymous types compare their properties by value, so two users fall into the same group when both properties are equal. A tuple, such as (user.LastName, user.Occupation), works the same way.

$ dotnet run
{ LastName = Doe, Occupation = gardener }
User { FirstName = John, LastName = Doe, Occupation = gardener }
----------------
{ LastName = Doe, Occupation = teacher }
User { FirstName = Jane, LastName = Doe, Occupation = teacher }
User { FirstName = Peter, LastName = Doe, Occupation = teacher }
----------------
{ LastName = Roe, Occupation = driver }
User { FirstName = Roger, LastName = Roe, Occupation = driver }
----------------
{ LastName = Novak, Occupation = programmer }
User { FirstName = Pavol, LastName = Novak, Occupation = programmer }
User { FirstName = Michael, LastName = Novak, Occupation = programmer }
----------------
{ LastName = Novak, Occupation = teacher }
User { FirstName = Albert, LastName = Novak, Occupation = teacher }
----------------
{ LastName = Novak, Occupation = driver }
User { FirstName = Sam, LastName = Novak, Occupation = driver }
----------------
{ LastName = Horvath, Occupation = accountant }
User { FirstName = Peter, LastName = Horvath, Occupation = accountant }
User { FirstName = Lucia, LastName = Horvath, Occupation = accountant }
----------------

Group by a boolean expression

The key can be the result of a condition, which splits the data into two groups.

Program.cs
Student[] students =
[
    new ("John", "Doe", 78),
    new ("Roger", "Roe", 89),
    new ("Peter", "Doe", 90),
    new ("Pavol", "Novak", 34),
    new ("Albert", "Novak", 66),
    new ("Peter", "Horvath", 89),
    new ("Lucia", "Horvath", 88),
    new ("Michael", "Novak", 99),
];

var groups = from student in students
             group student by student.Score > 70;

foreach (var group in groups)
{
    Console.WriteLine(group.Key ? "passed" : "failed");

    foreach (var e in group)
    {
        Console.WriteLine(e);
    }

    Console.WriteLine("----------------------------");
}

record Student(string FirstName, string LastName, int Score);

To pass an exam, a student needs a score over 70.

group student by student.Score > 70;

The key is a bool. Since the first student passed, the true group comes first.

$ dotnet run
passed
Student { FirstName = John, LastName = Doe, Score = 78 }
Student { FirstName = Roger, LastName = Roe, Score = 89 }
Student { FirstName = Peter, LastName = Doe, Score = 90 }
Student { FirstName = Peter, LastName = Horvath, Score = 89 }
Student { FirstName = Lucia, LastName = Horvath, Score = 88 }
Student { FirstName = Michael, LastName = Novak, Score = 99 }
----------------------------
failed
Student { FirstName = Pavol, LastName = Novak, Score = 34 }
Student { FirstName = Albert, LastName = Novak, Score = 66 }
----------------------------

Group by a range

A computed value can put numbers into ranges.

Program.cs
List<Student> students =
[
    new ("John", "Doe", 78),
    new ("Roger", "Roe", 89),
    new ("Peter", "Doe", 90),
    new ("Pavol", "Novak", 34),
    new ("Albert", "Novak", 66),
    new ("Peter", "Horvath", 89),
    new ("Lucia", "Horvath", 88),
    new ("Michael", "Novak", 99),
];

var groups = from std in students
             group std by (std.Score / 10) into g
             orderby g.Key
             select g;

foreach (var group in groups)
{
    Console.WriteLine($"{group.Key * 10}-{group.Key * 10 + 9}");

    foreach (var e in group)
    {
        Console.WriteLine(e);
    }

    Console.WriteLine("----------------------------");
}

record Student(string FirstName, string LastName, int Score);

Integer division by 10 maps scores 80 to 89 to the key 8, scores 90 to 99 to the key 9, and so on.

group std by (std.Score / 10) into g
orderby g.Key

The groups are sorted by their keys, so the ranges are printed in ascending order.

$ dotnet run
30-39
Student { FirstName = Pavol, LastName = Novak, Score = 34 }
----------------------------
60-69
Student { FirstName = Albert, LastName = Novak, Score = 66 }
----------------------------
70-79
Student { FirstName = John, LastName = Doe, Score = 78 }
----------------------------
80-89
Student { FirstName = Roger, LastName = Roe, Score = 89 }
Student { FirstName = Peter, LastName = Horvath, Score = 89 }
Student { FirstName = Lucia, LastName = Horvath, Score = 88 }
----------------------------
90-99
Student { FirstName = Peter, LastName = Doe, Score = 90 }
Student { FirstName = Michael, LastName = Novak, Score = 99 }
----------------------------

CountBy and AggregateBy

.NET 9 added the CountBy and AggregateBy methods. They compute a value per key directly, without creating groups of elements.

Program.cs
Order[] orders =
[
    new("Alice", "books", 25.5m),
    new("Bob", "games", 60m),
    new("Alice", "games", 45m),
    new("Carol", "books", 12m),
    new("Bob", "books", 18.25m),
    new("Alice", "music", 9.99m),
];

Console.WriteLine("Orders per customer:");
foreach (var (customer, count) in orders.CountBy(o => o.Customer))
{
    Console.WriteLine($"  {customer}: {count}");
}

Console.WriteLine();

var totals = orders.AggregateBy(
    o => o.Category,
    seed: 0m,
    (total, o) => total + o.Amount);

Console.WriteLine("Totals per category:");
foreach (var (category, total) in totals)
{
    Console.WriteLine($"  {category}: {total}");
}

record Order(string Customer, string Category, decimal Amount);

CountBy returns key-value pairs with the number of elements for each key.

var totals = orders.AggregateBy(
    o => o.Category,
    seed: 0m,
    (total, o) => total + o.Amount);

AggregateBy keeps an accumulator for each key. It starts at the seed value and is updated with every element of that key; here we sum the order amounts per category.

$ dotnet run
Orders per customer:
  Alice: 3
  Bob: 2
  Carol: 1

Totals per category:
  books: 55.75
  games: 105
  music: 9.99

ToLookup

The ToLookup method groups the elements immediately and returns an ILookup<TKey, TElement>, a read-only dictionary of groups.

Program.cs
Employee[] employees =
[
    new("John", "IT"),
    new("Jane", "HR"),
    new("Peter", "IT"),
    new("Lucy", "Sales"),
    new("Robert", "IT"),
];

ILookup<string, Employee> byDept = employees.ToLookup(e => e.Department);

Console.WriteLine($"Departments: {byDept.Count}");
Console.WriteLine($"IT: {string.Join(", ", byDept["IT"].Select(e => e.Name))}");
Console.WriteLine($"Has Finance: {byDept.Contains("Finance")}");
Console.WriteLine($"Finance: {byDept["Finance"].Count()} employees");

record Employee(string Name, string Department);

The lookup is indexed by key, which gives the elements with that key.

Console.WriteLine($"Finance: {byDept["Finance"].Count()} employees");

Unlike a dictionary, a lookup returns an empty sequence for a missing key instead of throwing an exception.

$ dotnet run
Departments: 3
IT: John, Peter, Robert
Has Finance: False
Finance: 0 employees

Deferred and immediate grouping

GroupBy uses deferred execution, while ToLookup groups the data at once.

Program.cs
List<string> colours = ["red", "green", "red"];

var groups = colours.GroupBy(c => c);
var lookup = colours.ToLookup(c => c);

colours.Add("blue");
colours.Add("red");

Console.WriteLine("GroupBy:");
foreach (var g in groups)
{
    Console.WriteLine($"  {g.Key}: {g.Count()}");
}

Console.WriteLine("ToLookup:");
foreach (var g in lookup)
{
    Console.WriteLine($"  {g.Key}: {g.Count()}");
}

Both groupings are created from the same list, and then two more elements are added.

colours.Add("blue");
colours.Add("red");

The GroupBy query runs when it is enumerated, so it sees the new elements. The lookup was built before the change and keeps the old data.

$ dotnet run
GroupBy:
  red: 3
  green: 1
  blue: 1
ToLookup:
  red: 2
  green: 1

Word frequency

In the following example, we count the frequency of words in a file. We use the King James Bible.

$ wget https://raw.githubusercontent.com/janbodnar/data/main/the-king-james-bible.txt
Program.cs
using System.Text.RegularExpressions;

string text = File.ReadAllText("the-king-james-bible.txt");

var words = Regex.Matches(text, @"\p{L}+(?:'\p{L}+)*")
    .Select(m => m.Value.ToLowerInvariant())
    .ToList();

var topTen =
    (from word in words
     group word by word into g
     orderby g.Count() descending
     select new { Word = g.Key, Total = g.Count() }
    ).Take(10);

foreach (var e in topTen)
{
    Console.WriteLine($"{e.Word}: {e.Total}");
}

Console.WriteLine();

var topFive = words.CountBy(w => w)
    .OrderByDescending(e => e.Value)
    .Take(5);

foreach (var (word, total) in topFive)
{
    Console.WriteLine($"{word}: {total}");
}

The program finds the ten most common words.

var words = Regex.Matches(text, @"\p{L}+(?:'\p{L}+)*")
    .Select(m => m.Value.ToLowerInvariant())
    .ToList();

A word is a sequence of letters, possibly with apostrophes inside, as in LORD's. The words are converted to lowercase so that And and and are counted together. The list is materialized because it is used by two queries.

var topTen =
    (from word in words
     group word by word into g
     orderby g.Count() descending
     select new { Word = g.Key, Total = g.Count() }
    ).Take(10);

The words are grouped by themselves, ordered by the size of the group in descending order, and the first ten are taken.

var topFive = words.CountBy(w => w)
    .OrderByDescending(e => e.Value)
    .Take(5);

CountBy gives the same counts without building groups that hold every occurrence of every word.

$ dotnet run
the: 64020
and: 51696
of: 34668
to: 13580
that: 12912
in: 12667
he: 10419
shall: 9838
unto: 8997
for: 8971

the: 64020
and: 51696
of: 34668
to: 13580
that: 12912

Source

Grouping data

In this article we have grouped data in C# with LINQ.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all C# tutorials.