C# Dictionary: CRUD

A dictionary (Dictionary<TKey, TValue>) in C# is a collection of objects that allow you to store and retrieve key-value pairs efficiently. In this blog, we will explore the C# dictionary and how it works.

What is a Dictionary?

A dictionary in C# is a collection of key-value pairs, where each key is unique. It is similar to a real-life dictionary, where the key is a word, and the value is its definition. The key-value pairs can be of any data type, such as string, int, bool, etc. The dictionary class in C# is part of the System.Collections.Generic namespace and it is implemented as a hash table.

Creating a Dictionary

You can create an empty dictionary in C# using the following snippet:

Dictionary<TKey, TValue> myDict = new Dictionary<TKey, TValue>();

Here, TKey represents the data type of the key, and TValue represents the data type of the value. For example, to create a dictionary of string keys and int values, you can use the following code:

Dictionary<string, int> myDict = new Dictionary<string, int>();

You can also initialize a dictionary with key-value pairs using the collection initializer syntax, as shown below:

Dictionary<string, int> myDict = new Dictionary<string, int>()
{
    {"red", 1},
    {"green", 2},
    {"orange", 3}
};

Adding and Accessing Elements in a Dictionary

To add an element to a dictionary, you can use the Add() method:

myDict.Add("blue", 4);

To retrieve an element from a dictionary, you can use its key as an index, as shown below snippet:

int value = myDict["red"];

If the key doesn't exist in the dictionary, an exception will be thrown. You can check if a key exists in the dictionary using the ContainsKey() method:

if (myDict.ContainsKey("red"))
{
    int value = myDict["red"];
    Console.WriteLine("The value of red is " + value);
}
else
{
    Console.WriteLine("The key 'red' does not exist in the dictionary.");
}

Removing Elements from a Dictionary

To remove an element from a dictionary, you can use the Remove() method,

myDict.Remove("red");

Iterating over a Dictionary

The dictionary can be iterated using a foreach loop,

foreach (KeyValuePair<string, int> kvp in myDict)
{
    Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
}

Advantages of using a Dictionary

The C# Dictionary provides several advantages over other collections such as lists or arrays.

Fast lookups: The dictionary is implemented as a hash table, which allows for constant-time lookups of key-value pairs. This is much faster than iterating over a list or array to find a specific value.

Flexibility: The key-value pairs can be of any data type, which makes the dictionary a flexible data structure that can be used in many different scenarios.

No duplicate keys allowed: Each key in the dictionary must be unique. If you attempt to add a key that already exists, it will replace the existing value.