Aggregate data with dictionaries
Use Dictionary<TKey, TValue> to group and sum by key.
- Build per-key totals with Dictionary and deterministic output.
Dictionary<TKey, TValue> maps keys to values for fast lookup and updates. Grouped totals are common in automation tasks: billing summaries, category metrics, and region reports. Use TryGetValue or ContainsKey to initialize totals before incrementing.
1using System;
2using System.Collections.Generic;
3
4class Program
5{
6 static void Main()
7 {
8 var totals = new Dictionary<string, int>();
9 totals["north"] = 4;
10 totals["north"] += 3;
11 Console.WriteLine(totals["north"]);
12 }
13}7
Dictionary does not guarantee insertion order, so format required output explicitly (for example north then south) when tests or integrations require deterministic text.
Key takeaways
Dictionary is ideal for grouped accumulation.
Define deterministic output ordering for reports.
Handle unknown keys explicitly.
Lesson quiz
5 questions · pass with 4 correct · up to 50 XP
Passing this quiz completes the lesson and keeps your streak going. Questions you miss come back in review sessions later.
Practice: write C#
Write C# 12 in the editor and run it against sample input. .NET 8 compiles and runs the code through Wandbox, a free public service; your source and test input are sent there.
Count tag frequency
Read integer n and then n lines, each a tag string. Print the count for the tag csharp.
- Two csharp tags
- No csharp tag
C# 12 code is compiled and run with .NET 8 on Wandbox, a free public service. Your source code and test input are sent to that service.
Questions about this lesson
Stuck? Ask. Figured something out? Share it. Explaining is one of the best ways to learn.
Loading posts…