Dictionary and Maps in C#
The Dictionary is a generic collection that holds data in key-value pairs. On the other hand, the map takes a sequence of objects, applies some change to each of them, and produces a new sequence containing the transformed items.
With this brief introduction, let us quickly begin this article on Dictionary and Maps in C#.
Table of contents
- Introduction to Dictionary in C#
- How to create a Dictionary in C#?
- Adding elements to the Dictionary in C#
- Accessing Key-Value pair in Dictionary in C#
- Update Dictionary
- Remove elements in the Dictionary
- Introduction to Map in C#
Introduction to Dictionary in C#
In C#, all dictionaries implement the IDictionary interface. There are various Dictionary types, but the generic Dictionary, often known as Dictionary<TKey, TValue>, is the most commonly used. It retains a type-specific key and a corresponding type-specific value. This is what distinguishes a Dictionary from a List. Elements in a list are arranged in a precise order and can be accessed using a numerical index, but objects in a Dictionary are stored with a unique key that can be used to retrieve them.
We'll delve more into dictionaries later, but first, let's look at a simple example
We will use the Doe family, who will serve as the test data for this tutorial's example - Joe and Jenna, the twins, and their parents John and Jane. Take note of how we have set up the Dictionary with a string as the key (in this example, the name) and an integer as the value (in this case the age).
The great part is that instead of utilizing a number index, we can use the key (name) to get an item from the dictionary. You can see this in action in the last line of the example, where we just declare the key to access the value between a set of square brackets (the age).
How to create a dictionary in C#?
We merely need to initialize as below to establish a dictionary with key and value types of string and int, respectively.
The first line will build a dictionary with a ‘string’ type key and an ‘int’ type value, as well as a default capacity and equality comparer for the key type.
Except for the initial default capacity, the second line will generate the same dictionary as the first. It will generate a dictionary with a capacity of 5 by default.
Using the dictionary's various constructors, we can build the dictionary. You've just seen the two constructors so far.
Adding elements to the dictionary in C#
If you wish to add elements to your Dictionary, use the Add() method to create key/value pairs. Without using the Add method, you can also add key/value pairs to the dictionary as seen in the case below:
Accessing Key-Value pair in Dictionary in C#
Following are the three ways of accessing values from a dictionary in C#:
Using For loop: As illustrated below, you can use the for loop to access the Dictionary's key/value pairs.
Using Index: The index value of a key/value pair in the Dictionary can be used to access it. You only need to mention the key in the index to receive the value from the given dictionary; the index is not required. The key is always passed as a parameter to the indexer, and if the key isn't found in the dictionary, it throws a KeyNotFoundException.
Using for-each loop: The for-each loop can be used to access the dictionary's key/value pairs. Here’s an example -
By defining a key in the indexer, you can change the value of a key. If a key does not exist in the dictionary, it will throw the KeyNotFoundException. So use the ContainsKey() function before accessing unknown keys.
Remove elements in the dictionary
A dictionary's Remove() method deletes an existing key-value pair. The Clear() method removes all the dictionary's elements.
Introduction to Map in C#
There is no built-in Map type in C#. It does, however, include a powerful Dictionary type, which we utilize to map objects. We must define the key type (such as "string") and the value type when using Dictionary. We map a key to a value with Add. We can safely check this mapping with TryGetValue.
For example, consider a map. We map strings to other strings in this section. Each string can only be mapped to one other string at a time (keys must be unique). Now cosider the following:
Dog, cat: The "cat" and "dog" strings are mapped to various color words using the Add method.
Foreach: We go through the map's keys and values in a loop. In the for-each loop, we access each KeyValuePair in the map.
TryGetValue: This is the most efficient way to get a value from a key in the map. If the key does not exist, it returns false.
The Dictionary is an essential component of C# programming and is simply a collection of Maps. Also remember - there is no built-in map in the C# language. For all of our mapping needs, we can utilize a Dictionary.. Dictionaries aid in the management of data in Key-Value pairs, allowing us to quickly access and alter the information.