C# 11 Dictionary Collections

C# dictionaries allow data to be stored and managed as key-value pairs. Dictionaries fulfill a similar purpose to arrays and lists, except each item stored in the dictionary has associated with it a unique key (to be precise, the key is unique to the particular dictionary object) which can be used to reference and access the corresponding value.

Dictionary initialization

A dictionary is a data type explicitly designed to hold multiple values in a single unordered collection. Each item in a dictionary consists of a key and an associated value.

The Dictionary class is contained within the  System.Collections.Generic namespace, which must be imported when working with lists.

An empty dictionary may be created using the following syntax:

Dictionary<key-type, value-type> name =
    new Dictionary<key-type, value-type>();Code language: C# (cs)

The following code, for example, creates an empty dictionary using an int for the key and a string for the values:

Dictionary<int, string> movies =
    new Dictionary<int, string>();Code language: C# (cs)

Alternatively, you can use implicit typing using the var keyword:

var movies =
    new Dictionary<int, string>();Code language: C# (cs)

A new dictionary may be initialized with a collection of values using a collection initializer with the following syntax (note that we are once again using implicit typing):

var name = new Dictionary<key-type, value-type>()
{
    { key1, value1 },
    { key2, value2 },
    { key3, value3 },
.
.
};Code language: C# (cs)

The following code creates a new dictionary initialized with four key-value pairs in the form of strings acting as keys for corresponding movie titles:

var movies = new Dictionary<string, string>()
{
    { "DRA-1212", "The Godfather" },
    { "WAR-4433", "Apocalypse Now" },
    { "COM-5465", "The Terminal" },
    { "CLA-1659", "Casablanca" }
};Code language: C# (cs)

In the above instance, the C# compiler will use implicit typing to decide that both the key and value elements of the dictionary are of string and prevent values or keys of other types from being inserted into the dictionary.

Dictionary item count

A count of the items in a dictionary can be obtained by accessing the dictionary’s Count property:

var movies = new Dictionary<string, string>()
    {
        { "DRA-1212", "The Godfather" },
        { "WAR-4433", "Apocalypse Now" },
        { "COM-5465", "The Terminal" },
        { "CLA-1659", "Casablanca" }
    };

System.Console.WriteLine($"Count = {movies.Count}");Code language: C# (cs)

Output:

Count = 4

Dictionary iteration

As with arrays and lists, you can iterate through all entries in a dictionary using foreach looping syntax. The following code, for example, iterates through all of the entries in the movies dictionary, outputting both the key and value for each entry:

var movies = new Dictionary<string, string>()
{
    { "DRA-1212", "The Godfather" },
    { "WAR-4433", "Apocalypse Now" },
    { "COM-5465", "The Terminal" },
    { "CLA-1659", "Casablanca" }
};

foreach (var movie in movies) {

    var key = movie.Key;
    var value = movie.Value;

    System.Console.WriteLine($"{key} - {value}");
}Code language: C# (cs)

Output:

DRA-1212 - The Godfather
WAR-4433 - Apocalypse Now
COM-5465 - The Terminal
CLA-1659 - Casablanca

As we can see in the above code, each entry within a dictionary has Key and Value properties. In this case, we have used these properties to extract each dictionary entry’s key and movie title value.

Adding and removing dictionary entries

New entries can be added to an existing dictionary by making a call to the Add() method of the instance, passing through the key/value pair:

var movies = new Dictionary<string, string>()
{
    { "DRA-1212", "The Godfather" },
    { "WAR-4433", "Apocalypse Now" },
    { "COM-5465", "The Terminal" },
    { "CLA-1659", "Casablanca" }
};

movies.Add("SCI-2323", "Prometheus");

System.Console.WriteLine(movies["SCI-2323"]);Code language: C# (cs)

Output:

Prometheus

You can remove an entry from a dictionary by calling the Remove() method, referencing the key matching the entry to be removed:

var movies = new Dictionary<string, string>()
{
    { "DRA-1212", "The Godfather" },
    { "WAR-4433", "Apocalypse Now" },
    { "COM-5465", "The Terminal" },
    { "CLA-1659", "Casablanca" }
};

movies.Remove("WAR-4433");

foreach (var movie in movies) {

    var key = movie.Key;
    var value = movie.Value;

    System.Console.WriteLine($"{key} - {value}");
}Code language: C# (cs)

Output:

DRA-1212 - The Godfather
COM-5465 - The Terminal
CLA-1659 - Casablanca

Accessing and updating dictionary items

A specific value may be accessed or modified using key subscript syntax to reference the corresponding value. The following code references a key known to be in the movies dictionary and outputs the associated value (in this case, the movie entitled “The Terminal” ):

var movies = new Dictionary<string, string>()
{
    { "DRA-1212", "The Godfather" },
    { "WAR-4433", "Apocalypse Now" },
    { "COM-5465", "The Terminal" },
    { "CLA-1659", "Casablanca" }
};

System.Console.WriteLine(movies["COM-5465"]);Code language: C# (cs)

Output:

The Terminal

Indexing by key may also be used when updating the value associated with a specified key, for example, to change the title of the same movie from “The Terminal” to “Caddyshack” ):

var movies = new Dictionary<string, string>()
{
    { "DRA-1212", "The Godfather" },
    { "WAR-4433", "Apocalypse Now" },
    { "COM-5465", "The Terminal" },
    { "CLA-1659", "Casablanca" }
};

movies["COM-5465"] = "Caddyshack";

System.Console.WriteLine(movies["COM-5465"]);Code language: C# (cs)

Output:

Caddyshack

Checking if a key or value exists

A dictionary can be searched to find out if it contains a particular key by calling the ContainsKey() method. Before adding new entries to a dictionary, you may want to call this method to ensure the key has not already been used to avoid a runtime exception error.

You can also check whether a specific value exists in a dictionary with a call to the ContainsValue() method. The following example demonstrates both of these methods in action:

var movies = new Dictionary<string, string>()
{
    { "DRA-1212", "The Godfather" },
    { "WAR-4433", "Apocalypse Now" },
    { "COM-5465", "The Terminal" },
    { "CLA-1659", "Casablanca" }
};

if (movies.ContainsKey("CLA-1659")) {
    System.Console.WriteLine("Key exists in dictionary");
}

if (movies.ContainsValue("The Godfather")) {
    System.Console.WriteLine("Title exists in dictionary");
}Code language: JavaScript (javascript)

Output:

Key exists in dictionary
Title exists in dictionary

Categories