Limited Offer
60% OFF on all plans!

Dictionary & SortedDictionary in C#

Store key-value pairs using Dictionary<TKey,TValue>, SortedDictionary, and ImmutableDictionary — CRUD operations, iteration, merging, and choosing the right type.

Dictionary Basics

1. Creating an Empty Dictionary

A `Dictionary<TKey, TValue>` maps keys to values. Keys must be unique.

2. Setting a Key-Value Pair

Use `dict[key] = value` to add or update a key.

3. Checking if a Key Exists

Use `ContainsKey()` before accessing to avoid a `KeyNotFoundException`.

4. Accessing Value on a Specific Key

Use `dict[key]` to get a value — throws if the key is missing.

5. Updating Value on a Specific Key

Use `dict[key] = newValue` to overwrite an existing entry.

6. Deleting a Key-Value Pair

Use `Remove()` to delete an entry by key.

7. Clearing the Dictionary

`Clear()` removes all entries but keeps the dictionary object.

8. Getting Dictionary Size

`Count` returns the number of key-value pairs.

Dictionary Keys & Values

1. Getting Keys List

`Keys` returns a `Dictionary<K,V>.KeyCollection` of all keys.

2. Getting Values List

`Values` returns a `Dictionary<K,V>.ValueCollection` of all values.

Traversing a Dictionary

1. Traversing using foreach (KeyValuePair)

The standard way — destructures into `Key` and `Value`.

2. Traversing using forEach (lambda)

Use LINQ `.ToList().ForEach()` to apply a lambda to each entry.

3. Traversing Keys Only

Iterate `.Keys` when you only need the keys.

Merging Dictionaries

1. Merging Two Dictionaries

Copy entries from one dictionary into another.

2. Merging with Conflict Strategy

When both dicts share a key, decide which value wins.

Dictionary Variants

1. SortedDictionary (Sorted by Key)

`SortedDictionary<K,V>` keeps keys in ascending order at all times.

2. ImmutableDictionary (Read-Only)

`ImmutableDictionary<K,V>` cannot be mutated after creation.

3. ConcurrentDictionary (Thread-Safe)

`ConcurrentDictionary<K,V>` is safe for use across multiple threads.