csharp-que-son-diccionarios

What are dictionaries and how to use them in C#

  • 5 min

A 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 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 duplicates and null.

If you want to learn more, check out the Introduction to Programming Course

Declaration and initialization of dictionaries

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

Dictionary<keyType, valueType> dictionaryName;
Copied!

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>();
Copied!

In this example, we have created a Dictionary named 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.

Or, 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 ();
Copied!

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 }
};
Copied!

Basic usage of the dictionary

Adding elements to a dictionary

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

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

Accessing elements of a dictionary

Elements of a dictionary can be accessed by their keys:

int ageOfLuis = ages["Luis"];
Copied!

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;
Copied!

Deleting elements from a dictionary

To delete elements from a dictionary

ages.Remove("Pedro");
Copied!

Enumerating elements in a dictionary

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

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

Clearing the entire dictionary

ages.Clear();
Copied!

Useful properties and methods

Count Property

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

int quantity = ages.Count;
Copied!

ContainsKey Method

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

bool containsLuis = ages.ContainsKey("Luis");
Copied!

ContainsValue Method

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

bool containsAge30 = ages.ContainsValue(30);
Copied!

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");
}
Copied!

Practical examples