Codiqo

Learn C# · lesson 33 of 61 · about 10 minutes

Project: Guild Leaderboard

Post the guild's leaderboard: keep each hero's XP in a Dictionary, then find the top hero, the average, the veterans and the tiers with LINQ.

What you'll learn

  • Parse name and number lines into a dictionary
  • Summarise with LINQ
  • Group results into tiers

The guild's leaderboard

Back in town, the adventurers' guild posts this week's XP. The hero's own XP is the damage done to the boss, bossHits.Sum(), and the other heroes' lines are typed in like Bo 120 until done. A Dictionary<string, int> holds each name's XP (typing a name again replaces it), and LINQ answers the guild's questions: who's on top, what the average is, who's a veteran with 50 XP or more, and how many heroes are in each tier.

The plan

1. Start the guild with the hero and bossHits.Sum()
2. Read name xp lines until done, skipping any without a name and a number
3. Print the top hero and the average
4. List the veterans, then count the heroes in each tier

Class statistics

Dictionary<string, int> scores = new();
string? line;
while (!string.IsNullOrWhiteSpace(line = Console.ReadLine()))
{
    string[] parts = line.Split(' ');
    scores[parts[0]] = int.Parse(parts[1]);
}

var top = scores.OrderByDescending(kv => kv.Value).First();
Console.WriteLine($"Top: {top.Key} ({top.Value})");
Console.WriteLine($"Average: {scores.Values.Average():F1}");
Console.WriteLine($"Passed: {string.Join(", ", scores.Where(kv => kv.Value >= 50).Select(kv => kv.Key))}");

var bands = scores.Values
    .GroupBy(s => s >= 70 ? "A" : s >= 50 ? "B" : "C")
    .OrderBy(g => g.Key);
foreach (var g in bands) Console.WriteLine($"{g.Key}: {g.Count()}");

Output

Top: Ada (88)
Average: 59.4
Passed: Ada, Cy, Dee
A: 2
B: 1
C: 2

Tip

string? is a string that might be null. string.IsNullOrWhiteSpace handles null, empty and spaces at once, and after it the compiler knows line isn't null.

Tip

OrderByDescending keeps equal items in the order they came in, so when two heroes tie, the one added first stays on top. Here that's the hero, who's always added first.

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.