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 class Dictionary<TKey, TValue>
in the namespace System.Collections.Generic
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.
If you want to learn more about Dictionaries
check the Introduction to Programming Course read more
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 their 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 is declared, before we can use it, we must initialize it. To do this, we need to 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 ();
Initialization of dictionaries
Alternatively, we can also initialize the dictionary to a series of known values.
Dictionary<string, int> ages = new ()
{
{ "Luis", 25 },
{ "María", 30 },
{ "Pedro", 28 }
};
Basic usage of the dictionary
Adding elements to a dictionary
To add elements to a dictionary, you can use the Add
method or the key index:
ages.Add("Luis", 32);
ages["Ana"] = 22;
Accessing elements of a dictionary
Elements of a dictionary can be accessed by their keys:
int ageOfLuis = ages["Luis"];
Modifying elements of a dictionary
To modify the value associated with an existing key, simply assign a new value to that key:
ages["María"] = 35;
Removing elements from a dictionary
To remove elements from a dictionary:
ages.Remove("Pedro");
Enumerating elements in a dictionary
To iterate through all the elements of a dictionary, you can use a foreach
loop:
foreach (var item in ages)
{
Console.WriteLine($"Name: {item.Key}, Age: {item.Value}");
}
Clearing the entire dictionary
ages.Clear();
Useful properties and methods
Count Property
The Count
property returns the number of key-value pairs in the dictionary:
int quantity = ages.Count;
ContainsKey Method
The ContainsKey
method checks if a specific key is present in the dictionary:
bool containsLuis = ages.ContainsKey("Luis");
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 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}");
}
else
{
Console.WriteLine("Luis is not in the dictionary");
}
:::::::
Practical examples
Storing student information and their grades
In this example, it shows how to store the grades of several students in a dictionary and calculate the average for each one.
// Create a dictionary to store the students' grades
var studentGrades = new Dictionary<string, List<int>>();
// Add grades for each student
studentGrades["Luis"] = new List<int> { 90, 85, 88 };
studentGrades["María"] = new List<int> { 95, 92, 89 };
studentGrades["Pedro"] = new List<int> { 78, 84, 80 };
// Iterate over the dictionary and calculate the average for each student
foreach (var student in studentGrades)
{
string name = student.Key; // Student's name
var grades = student.Value; // List of the student's grades
double average = grades.Average(); // Calculate the average
Console.WriteLine($"Student: {name}, Average: {average}");
}
Searching for the price of a specific product
In this example, it shows how to search for the price of a specific product using a dictionary.
// Create a dictionary to store product prices
var productPrices = new Dictionary<string, double>();
// Add prices for each product
productPrices["Apple"] = 1.2;
productPrices["Banana"] = 0.5;
productPrices["Orange"] = 0.8;
// Search for the price of a specific product
string productToSearch = "Banana";
if (productPrices.TryGetValue(productToSearch, out double price))
{
Console.WriteLine($"Product: {productToSearch}, Price: {price}");
}
else
{
Console.WriteLine($"The product {productToSearch} is not found in the dictionary.");
}
Searching for the department of a list of employees
In this example, it shows how to use a dictionary for quick searches. Assuming we have a dictionary that has each person’s department, and a very long list of people we want to search for.
// Create a dictionary to store employee departments
// Assuming '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}");
}
else
{
Console.WriteLine($"The employee {employeeToSearch} is not found in the dictionary.");
}
}
:::::::