Language: EN


What are dictionaries and how to use them in C#

A Dictionary in C# is a generic collection that allows you to store key-value pairs. They provide a very efficient way to perform searches, insertions, and deletions.

The Dictionary<TKey, TValue> class in the System.Collections.Generic namespace is the standard implementation of this data structure in C#.

Keys must be unique and cannot be null, while values can be duplicated and null.

Declaration and initialization of dictionaries

To declare a dictionary in C#, the following syntax is used:

Dictionary<keyType, valueType> dictionaryName;

For example, if we want to create a Dictionary that stores people’s names and ages, we can use the following syntax:

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

In this example, we have created a Dictionary called ages that uses strings as keys and integers as values.

Creating a dictionary

Once the dictionary has been declared, before we can use it, we must initialize it. To do this, we must create a new dictionary and assign it to the variable we declared earlier.

Alternatively, we can do it at the same time we declare our Dictionary. Like this:

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

// equivalent
var ages = new Dictionary<string, int>();
Dictionary<string, int> ages = new ();

Dictionary initialization

Alternatively, we can also initialize the dictionary to a series of known values.

Dictionary<string, int> ages = new ()
    { "Juan", 25 },
    { "María", 30 },
    { "Pedro", 28 }

Basic use of the dictionary

Adding elements to a dictionary

To add elements to a dictionary, the Add method or the key index is used:

ages.Add("Luis", 32);
ages["Ana"] = 22;

Accessing dictionary elements

Dictionary elements can be accessed by their keys:

int juansAge = ages["Juan"];

Modifying dictionary elements

To modify the value associated with an existing key, simply assign a new value to that key:

ages["María"] = 35;

Deleting dictionary elements

To delete elements from a dictionary


Enumerating elements in a dictionary

To iterate through all the elements of a dictionary, a foreach loop can be used:

foreach (var item in ages)
    Console.WriteLine($"Name: {item.Key}, Age: {item.Value}");

Clearing the entire dictionary


Useful properties and methods of Dictionary<TKey, TValue>

Count property

The Count property returns the number of key-value pairs in the dictionary:

int numberOfElements = ages.Count;

ContainsKey method

The ContainsKey method checks if a specific key is present in the dictionary:

bool containsJuan = ages.ContainsKey("Juan");

ContainsValue method

The ContainsValue method checks if a specific value is present in the dictionary:

bool containsAge30 = ages.ContainsValue(30);

TryGetValue method

The TryGetValue method attempts to get the value associated with a key, returning a Boolean value that indicates whether the operation was successful:

int age;
bool exists = ages.TryGetValue("Luis", out age);

if (exists)
    Console.WriteLine($"Luis's age is: {age}");
    Console.WriteLine("Luis is not in the dictionary");

Practical examples

Storing information about students and their grades

In this example, we show how to store the grades of various students in a dictionary and calculate the average of each one.

// Create a dictionary to store the students' grades
var studentGrades = new Dictionary<string, List<int>>();

// Add grades for each student
studentGrades["Juan"] = new List<int> { 90, 85, 88 };
studentGrades["María"] = new List<int> { 95, 92, 89 };
studentGrades["Pedro"] = new List<int> { 78, 84, 80 };

// Iterate through the dictionary and calculate each student's average
foreach (var student in studentGrades)
    string name = student.Key; // Student's name
    var grades = student.Value; // List of student's grades
    double average = grades.Average(); // Calculate the average

    Console.WriteLine($"Student: {name}, Average: {average}");

Finding the price of a specific product

In this example, we show how to find the price of a specific product using a dictionary.

// Create a dictionary to store the prices of the products
var productPrices = new Dictionary<string, double>();

// Add prices for each product
productPrices["Apple"] = 1.2;
productPrices["Banana"] = 0.5;
productPrices["Orange"] = 0.8;

// Find the price of a specific product
string productToFind = "Banana";
if (productPrices.TryGetValue(productToFind, out double price))
    Console.WriteLine($"Product: {productToFind}, Price: {price}");
    Console.WriteLine($"The product {productToFind} is not in the dictionary.");

Finding the department of a list of employees

In this example, we show how to use a dictionary for quick searches. Assuming that we have a dictionary that has the department of each person, and a very long list of people we want to search.

// Create a dictionary to store the departments of the employees
// We assume that 'employeeDepartments' is already populated with thousands of entries
var employeeDepartments = new Dictionary<string, string>();

// List of employees to search for
// In the example there are 5 people, but let's assume this list is very very large
List<string> employeesToSearch = [ "Ana", "Luis", "Carlos", "Pedro", "María" ];

// Perform quick searches using the dictionary
foreach (string employeeToSearch in employeesToSearch)
    if (employeeDepartments.TryGetValue(employeeToSearch, out string department))
        Console.WriteLine($"Employee: {employeeToSearch}, Department: {department}");
        Console.WriteLine($"The employee {employeeToSearch} is not in the dictionary.");