Dictionary
Explore how to utilize the Dictionary<TKey, TValue> collection in C# for quick and efficient data retrieval using unique keys. Learn to create, add, update, and merge dictionaries, manage key-value pairs, and implement safe access methods like TryAdd and TryGetValue. Understand the advantages of dictionaries over lists for large datasets and get practical insights into handling real-world scenarios such as counting character occurrences and merging collections.
We'll cover the following...
We’ve explored collections like lists, stacks, and queues. While these are excellent for managing sequences of data, they rely on sequential ordering or numeric indices to retrieve items. But what if we need to look up a user’s profile using their email address, or find a product’s price using its barcode? Searching through a massive list item by item would be incredibly slow.
To solve this, .NET provides the dictionary. This collection is optimized for fast lookups using unique keys instead of numeric indices. Because dictionaries use hashing internally, retrieving a value by its key operates in
Dictionaries are key-value stores. These are mappings between keys and associated values. Think of a dictionary like a physical translation book where the words serve as unique keys and the translations serve as the values:
Keys in .NET dictionaries must be unique. However, multiple keys can map to the same value.
Syntax
Dictionaries in .NET are created by instantiating the Dictionary<TKey, TValue> class. We can use any type as a key and any type as a value:
// Keys are of string type, values are of string typeDictionary<string, string> countryCapitalMapping = [];