C# Dictionary
A Dictionary<TKey, TValue> stores data as key-value pairs, letting you look up a value quickly using its unique key instead of a numeric index.
Dictionaries are ideal for scenarios like storing a phone book (name โ number) or counting word occurrences (word โ count), where you need fast lookups by a meaningful identifier.
Dictionary<TKey, TValue> name = new Dictionary<TKey, TValue>();
name[key] = value;Creating and using a Dictionary
A Dictionary is declared with two type parameters: the key type and value type, like `Dictionary<string, int> ages = new Dictionary<string, int>();`. Use square brackets to add or access values by key.
Checking and looping
ContainsKey() checks if a key exists before accessing it to avoid errors. You can loop through a dictionary with foreach, getting each item as a KeyValuePair.
using System;
using System.Collections.Generic;
class Program {
static void Main() {
Dictionary<string, int> ages = new Dictionary<string, int>();
ages["Amy"] = 25;
ages["Bob"] = 30;
Console.WriteLine(ages["Amy"]);
}
}25The value 25 is stored under the key "Amy" and retrieved using square brackets.
using System;
using System.Collections.Generic;
class Program {
static void Main() {
Dictionary<string, int> ages = new Dictionary<string, int> { { "Amy", 25 }, { "Bob", 30 } };
foreach (KeyValuePair<string, int> pair in ages) {
Console.WriteLine(pair.Key + ": " + pair.Value);
}
}
}Amy: 25
Bob: 30foreach iterates over each key-value pair in the dictionary.
Key points
- Dictionary<TKey, TValue> stores key-value pairs.
- Keys must be unique within a dictionary.
- ContainsKey() safely checks if a key exists before accessing it.
- foreach with KeyValuePair<TKey, TValue> iterates over all entries.
