Language: EN

csharp-que-son-diccionarios

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 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.

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

:::::::

Practical examples

:::::::