Lesson 9 of 15

Dictionaries

Dictionaries

Dictionary<TKey, TValue> maps keys to values (like a hash map):

var ages = new Dictionary<string, int>();
ages["Alice"] = 30;
ages["Bob"] = 25;
ages["Carol"] = 35;

Console.WriteLine(ages["Alice"]);     // 30
Console.WriteLine(ages.Count);       // 3
Console.WriteLine(ages.ContainsKey("Bob")); // True

Iterating

foreach (var pair in ages) {
    Console.WriteLine($"{pair.Key}: {pair.Value}");
}

Safe Lookup

if (ages.TryGetValue("Dave", out int age)) {
    Console.WriteLine(age);
} else {
    Console.WriteLine("Not found");
}

Your Task

Write a static method WordCount(string[] words) that returns a Dictionary<string, int> counting occurrences of each word. Then print the count for "hello" given the input ["hello", "world", "hello", "csharp", "hello"].

WasmSharp (.NET) loading...
Loading...
Click "Run" to execute your code.