We all know the meaning of Dictionary in general terms, Dictionary is a collection of words arranged alphabetically and each word has its own meaning. In C# the concept of Dictionary is almost same let’s read what is a dictionary and how we can play with code.
The Dictionary class in C# represents a generic data structure that can contain keys and values of data. Hence, you can store data of any type in an Instance of Dictionary. The Dictionary class is contained inside the System.Collections.Generic namespace. It Initializes a new instance of the System.Collections.Generic.Dictionary class that is empty, has the default initial capacity and uses the default equality in order to compare for the key type. In essence, a Dictionary<TKey, TValue> contains a generic collection of key/value pairs. You can use Add method of the Dictionary class to store objects in a Dictionary instance. Let’s learn about Dictionary with examples.
Initializing a Dictionary with a Collection Initializer
To initialize a Dictionary<TKey,TValue>, or any collection whose Add method takes multiple parameters, enclose each set of parameters in braces as shown in the following example.
Adding to a Dictionary
Retrieving a value from a dictionary
Reading a value or entire list from a dictionary is never been a big task, we can read it with different ways. either we iterate and display all records or get a single record.
You may want to read the value for the entry with key 1. If the key doesn’t exist getting a value, It will throw KeyNotFoundException, so you may want to first check for that with ContainsKey. This has one disadvantage: you will search through your dictionary twice (once to check for existence and one to read the value). For a large dictionary this can impact performance. Fortunately both operations can be performed together.
Convert IEnumerable to Dictionary
There can be a situation where you need to convert LINQ result or IEnumerable<> object into Dictionary object. This is possible with the help of the LINQ Extension methods.
In this example, we convert One LINQ’s IEnumerable<> result into Dictionary object. We are taking Month list object and then querying that object using LINQ and then we converted it’s LINQ result into Dictionary object.
What Next ?
In the next article, we will learn about ConcurrentDictionary in C#. Till then Keep learning and sharing. Happy Coding 🙂