An Dictionary in C# is a generic collection that allows storing key-value pairs. They provide a very efficient way to perform searches, insertions, and deletions.
The class Dictionary<TKey, TValue>
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 can be 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.
Creation of 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, the Add
method or the key index is used:
ages.Add("Luis", 32);
ages["Ana"] = 22;
Accessing Elements of a Dictionary
The 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 over all 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
ages.Clear();
Useful Properties and Methods of Dictionary<TKey, TValue>
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 value indicating 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 of each.
// Create a dictionary to store student 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; // Student's list of 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 contains the department of each person, and a very long list of people we want to search.
// Create a dictionary to store employee departments
// Suppose 'employeeDepartments' is already populated with thousands of entries
var employeeDepartments = new Dictionary<string, string>();
// List of employees to search
// 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.");
}
}