Aggregation and Grouping with LINQ

Summarize and organize your data

Posted by Rodrigo Castro on December 18, 2024

LINQ can do more than filter and sort: it can summarize and group your data.

➕ Aggregation: Sum, Count, Average, Min, Max

1
2
3
4
5
6
int[] numbers = { 1, 2, 3, 4, 5 };
int sum = numbers.Sum();        // 15
int count = numbers.Count();    // 5
double avg = numbers.Average(); // 3
int min = numbers.Min();        // 1
int max = numbers.Max();        // 5

👥 Grouping with GroupBy

1
2
3
4
5
6
7
8
string[] fruits = { "Apple", "Avocado", "Banana", "Apricot" };
var groups = fruits.GroupBy(f => f[0]);
foreach (var group in groups)
{
    Console.WriteLine($"Fruits starting with {group.Key}:");
    foreach (var fruit in group)
        Console.WriteLine(fruit);
}

💡 Try It!

Count how many times each word appears in a list:

1
2
3
4
5
string[] words = { "cat", "dog", "cat", "bird" };
var counts = words.GroupBy(w => w)
                  .Select(g => new { Word = g.Key, Count = g.Count() });
foreach (var item in counts)
    Console.WriteLine($"{item.Word}: {item.Count}");

Next: LINQ with objects!