Learn C# · lesson 32 of 61 · about 9 minutes
LINQ: Order, Sum and Group
Open the boss's treasure: group what drops with GroupBy, sort it, and add up its worth with Sum.
What you'll learn
- Sort with OrderBy and OrderByDescending
- Summarise with Sum, Average, Max, Count, Any and First
- Group items with GroupBy
The boss's treasure
The boss is down, and treasure spills out: coins, gems, maybe a crown, typed one at a time until done. The hero wants to know what's in the pile and what it's worth. GroupBy(x => x) gathers equal items into groups, each with a Key and a Count(), sorting with OrderBy first puts the groups in alphabetical order, and Sum adds up every item's worth, read from a second dictionary, in one call.
Summaries
| Method | Gives |
|---|---|
| OrderBy(x => key) / OrderByDescending | sorted items |
| Take(n) | the first n |
| Sum, Average, Min, Max | one number |
| Count(test) | how many pass |
| Any(test) | is at least one true? |
| First(test) | the first match |
| GroupBy(x => key) | groups with a .Key |
A leaderboard
var players = new[]
{
(Name: "Ada", Xp: 340, Lang: "C#"),
(Name: "Bo", Xp: 120, Lang: "Python"),
(Name: "Cy", Xp: 510, Lang: "C#"),
(Name: "Dee", Xp: 260, Lang: "Python"),
};
foreach (var p in players.OrderByDescending(p => p.Xp).Take(2))
{
Console.WriteLine($"{p.Name} {p.Xp}");
}
Console.WriteLine($"Total {players.Sum(p => p.Xp)}, average {players.Average(p => p.Xp)}");
Console.WriteLine($"{players.Count(p => p.Xp > 200)} over 200, any over 500: {players.Any(p => p.Xp > 500)}");
foreach (var g in players.GroupBy(p => p.Lang))
{
Console.WriteLine($"{g.Key}: {string.Join(", ", g.Select(p => p.Name))}");
}Output
Cy 510
Ada 340
Total 1230, average 307.5
3 over 200, any over 500: True
C#: Ada, Cy
Python: Bo, DeeTip
(Name: "Ada", Xp: 340) is a tuple: a quick way to bundle a few named values. In Chapter 4 you'll make proper classes and records.
Tip
Sum of nothing is 0, but Average, Max, Min and First throw an InvalidOperationException on an empty sequence. Check with Any() first when the list might be empty.
Now try it yourself
This lesson is free in Codiqo, with 8 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.