In C#, Dictionary<TKey,TValue> is a collection that stores pairs: a key and the value that belongs to it. Think of a phone book. You look up a name (the key) and get a number (the value). You add pairs with Add(), read them with TryGetValue(), and delete them with Remove().
Every key must be unique, but values may repeat. A dictionary finds a value from its key in about O(1) time, which is much faster than scanning a list. It lives in the System.Collections.Generic namespace, so add using System.Collections.Generic; at the top of your file.
A Dictionary often returns pairs in the order you added them, but that is not guaranteed. When you need a fixed order, sort the keys or use SortedDictionary.
Syntax
C# Syntax
Common first steps:
C#
using System.Collections.Generic;
Dictionary<string, int> ages = new Dictionary<string, int>();
ages.Add("Asha", 25); // add a new pair
ages["Ravi"] = 31; // indexer: add or overwrite
int a = ages["Asha"]; // read (throws if the key is missing)
bool ok = ages.TryGetValue("Zed", out int z); // read safely
int total = ages.Count; // number of pairs
Reference
Dictionary vs List and Array
Pick the collection that matches how you will look things up:
Type
You find items by
Good for
Dictionary<TKey,TValue>
Key (a name, an id, a code)
Lookups, counters, caches, settings
List<T>
Position (0, 1, 2) or by searching
An ordered list that grows and shrinks
T[] (array)
Position (0, 1, 2)
A fixed number of items
Reference
Indexer, Add, TryAdd, and TryGetValue
These four are the ones beginners use most. They behave differently when the key exists or is missing:
It is a collection of key and value pairs in System.Collections.Generic. Each key is unique, and you use the key to find its value very quickly.
A List stores items by position (0, 1, 2) and you search it item by item. A Dictionary stores pairs by key and finds a value directly from its key.
No. Add throws ArgumentException for a repeated key, TryAdd returns false, and the indexer overwrites the old value. Values may repeat.
You should not rely on any order. It often returns pairs in the order they were added, but that is not guaranteed. Use SortedDictionary if you need sorted keys.
Open the C# Dictionary Methods index. It lists Add, TryAdd, ContainsKey, ContainsValue, TryGetValue, Remove, Clear, EnsureCapacity, TrimExcess, and GetEnumerator.