Table of Contents
1 - What is a Dictionary in C#?
In C#, we have the dictionary type which is a collection that allows us to store data in a key-value
fashion; It uses specific types through generics both for its key and for its value.
A dictionary is described by the type Dictionary<TKey, TValue>
and under the hood it uses KeyValuePair<TKey, TValue>
for each of its elements.
This means that the value we use as the Key must be unique.
Previously, we used Hashtable
, but with the arrival of generics, we now use Dictionary
. This is because for hashtable
to work, we store the object as type Object
, which involves boxing
and unboxing
with every operation, and does not have the advantages of generics.
2 - Creating a dictionary and adding elements in C#
To create a dictionary in C#, we just need to instantiate it, and to add elements we can do it at instantiation, or through the .Add()
method.
//initialization and creating values
Dictionary<string, string> comunidadesCapitales = new Dictionary<string, string>()
{
{"Aragon", "Zaragoza"},
{"Navarra", "Pamplona"}
};
//add values
comunidadesCapitales.Add("Castilla la mancha", "Toledo");
As I mentioned, the key must be unique, so the "comunidad autónoma" cannot be repeated; if you try to add “Aragon”
again, it will throw an exception.
3 - Accessing the elements of a dictionary in C#
To access the elements of a dictionary, we do so through the indexer. You need to use the type of key you used when creating your dictionary.
And when you print it out, it returns the value:
Console.WriteLine(comunidadesCapitales["Aragon"]); //returns Zaragoza
If what you want is to access by position, you can do so through the .ElementAt(position)
method;
But in this case, it returns a KeyValuePair<TKey, TValue>
so to print the value, you must access .Value
:
KeyValuePair<string, string> resultado = comunidadesCapitales.ElementAt(0);
Console.WriteLine(resultado.Value); //returns Zaragoza
3.1 - The optimal way to access elements in a C# dictionary
The most optimal way to access elements of a dictionary is to use .TryGetValue()
. This is because if you try to access a non-existent element through the indexer, it will throw an exception, while with TryGetValue()
it will not.
But it works a bit differently. When you call .TryGetValue()
, what you are doing is checking if the value exists, so the method returns a boolean true
or false
.
And the actual value of the element is returned by the out parameter
of the method:
if (comunidadesCapitales.TryGetValue("Aragon", out string resultadoCapital))
{
Console.WriteLine(resultadoCapital); //zaragoza
}
else
{
Console.WriteLine("the parameter does not exist");
}
3.2 - Updating elements in a dictionary
To access elements in a dictionary, we use the indexer, but for that, we need to check if the value exists. We can use the .ContainsKey()
method, which will return true or false, and once we know it exists, we can change it.
if(comunidadesCapitales.ContainsKey("Aragon"))
{
comunidadesCapitales["Aragon"] = "Teruel Existe";
}
3.3 - Removing elements from a dictionary in C#
If you want to remove elements from a dictionary, you must use the .Remove(key)
method; but you have to be careful, because if the key does not exist, it will throw an exception.
And optionally you can run .Clear()
which will clear all the elements.
comunidadesCapitales.Remove("Aragon");
comunidadesCapitales.Clear();
Conclusion
In this post we have seen how to create dictionaries and add elements
How to read elements from a dictionary
How to remove elements from a dictionary
If there is any problem you can add a comment bellow or contact me in the website's contact form