The Role of Dictionaries in C#: Efficient Key-Value Storage

Dictionaries in C# are a type of collection that allows you to store key-value pairs, where each key is associated with a value.

Key-value pairs are commonly used to represent mappings between entities in a program, so this makes dictionaries an important data structure in C#. By using a dictionary, you can quickly and easily look up the value associated with a given key, which can be much faster than searching through a list or array.

Dictionaries are easy to use, but that is not the only reason to use them. Some of the reasons why dictionaries are important in C# include:

  1. Fast lookups – Dictionaries are implemented using a hash table, which means that looking up a value based on its key is very fast. In fact, the lookup time is typically O(1), which means that it is constant time and does not depend on the size of the dictionary.
  2. Efficient storage – Dictionaries only store the key-value pairs that are actually in use, which can be more memory-efficient than using an array or list to store the same data.
  3. Flexible keys – Dictionaries can use any type of object as a key, as long as it is hashable and supports equality comparison. This means that you can use complex objects or user-defined types as keys, which can be useful in a wide variety of scenarios.

Here are some of the top methods for working with dictionaries in C#:

Add(key, value)

Adds a new key-value pair to the dictionary.

Dictionary<string, int> scores = new Dictionary<string, int>();
scores.Add("John", 90);
scores.Add("Sarah", 80);
ContainsKey(key)

It is used to check if the dictionary contains a specific key

if (scores.ContainsKey("Sarah"))
{
    Console.WriteLine("Sarah's core is " + scores["Sarah"]);
}
TryGetValue(key, out value)

Attempts to retrieve the value associated with a key. Returns true if the key is found, false otherwise

int score;
if (scores.TryGetValue("John", out score))
{
    Console.WriteLine("John's score is " + score);
}
else
{
    Console.WriteLine("John's score is unknown");
}
Keys

Gets a collection of all keys in the dictionary

foreach (string name in scores.Keys)
{
    Console.WriteLine(name + " scored " + scores[name]);
}

The result of the code above would look like below

John scored 90
Sarah scored 80
Values

Gets a collection of all values in the dictionary

foreach (int score in scores.Values)
{
    Console.WriteLine("Score: " + score);
}

The result would be like below

Score 90
Score 80
Count

Gets the number of key-value pairs in the dictionary

Console.WriteLine("Number of scores: " + scores.Count);

Result

Number of scores: 2
Remove(key)

Removes a key-value pair from the dictionary.

scores.Remove("Alice");

A recap…

Below there is an example that demonstrates how to use some of these methods together:

Dictionary<string, int> scores = new Dictionary<string, int>();
scores.Add("John", 90);
scores.Add("Sarah", 80);

if (scores.ContainsKey("John"))
{
    int johnScore;
    if (scores.TryGetValue("John", out johnScore))
    {
        Console.WriteLine("John's score is " + johnScore);
    }
    else
    {
        Console.WriteLine("John's score is unknown");
    }
}

foreach (string name in scores.Keys)
{
    Console.WriteLine(name + " scored " + scores[name]);
}

scores.Remove("Sarah");

Console.WriteLine("Number of scores: " + scores.Count);

Result

Code result

Image by upklyak on Freepik


Enjoyed this post? Subscribe to my YouTube channel for more great content. Your support is much appreciated. Thank you!


Check out my Udemy profile for more great content and exclusive learning resources! Thank you for your support.
Ervis Trupja - Udemy



Enjoyed this blog post? Share it with your friends and help spread the word! Don't keep all this knowledge to yourself.