Dictionaries in C#
Key to value in constant time, with a safe way to ask for what might be missing.
var ages = new Dictionary<string, int>
{
["Ada"] = 36, ["Grace"] = 45, ["Alan"] = 41,
};
ages["Edsger"] = 72;
// TryGetValue avoids the exception a missing key would throw
if (ages.TryGetValue("Grace", out var age))
{
Console.WriteLine($"Grace is {age}");
}
foreach (var (name, years) in ages)
{
Console.WriteLine($"{name}: {years}");
}
How it works
- The index initializer reads like the lookups it will serve.
TryGetValueavoids the exception a missing key would throw.foreachover a dictionary deconstructs each pair into name and value.
Keywords and builtins used here
foreachifinintnewoutstringvar
The run, in numbers
- Lines
- 15
- Characters to type
- 337
- Tokens
- 79
- Three-star pace
- 90 tpm
At the three-star pace of 90 tokens a minute, this run takes about 53 seconds.
Step 3 of 4 in Collections, step 13 of 29 in Language basics.