ZetCode

C# Dictionary

last modified July 5, 2023

C# Dictionary tutorial shows how to work with a Dictionary collection in C#.

C# Dictionary

A dictionary, also called an associative array, is a collection of unique keys and a collection of values, where each key is associated with one value. Retrieving and adding values is very fast. Dictionaries take more memory because for each value there is also a key.

C# Dictionary initializers

C# dictionaries can be initialized with literal notation. The elements are added on the right side of the assignment inside {} brackets.

Program.cs
var domains = new Dictionary<string, string>
{
    {"sk", "Slovakia"},
    {"ru", "Russia"},
    {"de", "Germany"},
    {"no", "Norway"}
};

Console.WriteLine(domains["sk"]);

var days = new Dictionary<string, string>
{
    ["mo"] =  "Monday",
    ["tu"] =  "Tuesday",
    ["we"] =  "Wednesday",
    ["th"] =  "Thursday",
    ["fr"] =  "Friday",
    ["sa"] =  "Saturday",
    ["su"] =  "Sunday"
};

Console.WriteLine(days["fr"]);

In the example, we create two dictionaries using literal notation.

var domains = new Dictionary<string, string>
{
    {"sk", "Slovakia"},
    {"ru", "Russia"},
    {"de", "Germany"},
    {"no", "Norway"}
};

A new dictionary is created. Between the angle brackets <>, we specify the data type of the keys and values. New pairs of key/value elements are written inside nested {} brackets; each pair is separated by a comma character. For instance, the "sk" key refers to the "Slovakia" value.

Console.WriteLine(domains["sk"]);

To get a value, we specify the dictionary name followed by square [] brackets. Between the brackets, we specify the key name.

var days = new Dictionary<string, string>
{
    ["mo"] =  "Monday",
    ["tu"] =  "Tuesday",
    ["we"] =  "Wednesday",
    ["th"] =  "Thursday",
    ["fr"] =  "Friday",
    ["sa"] =  "Saturday",
    ["su"] =  "Sunday"
};

This is an alternative C# dictionary initializer. The values are assigned to keys using dictionary access notation.

$ dotnet run
Slovakia
Friday

C# Dictionary count elements

With the Count property, we get the number of keys in the dictionary.

Program.cs
var domains = new Dictionary<string, string>
{
    {"sk", "Slovakia"},
    {"ru", "Russia"},
    {"de", "Germany"},
    {"no", "Norway"}
};

domains.Add("pl", "Poland");

Console.WriteLine($"There are {domains.Count} items in the dictionary");

The example counts the number of items in the dictionary.

Console.WriteLine($"There are {domains.Count} items in the dictionary");

Here we print the number of items in the dictionary.

$ dotnet run
There are 5 items in the dictionary

C# Dictionary add, remove elements

After the dictionary has been created, new elements can be added or removed from the dictionary.

Program.cs
var users = new Dictionary<string, int>()
{
    { "John Doe", 41 },
    { "Jane Doe", 38 },
    { "Lucy Brown", 29 },
};

users["Paul Brown"] = 33;
users.Add("Thomas Pattison", 34);

Console.WriteLine(string.Join(", ", users));

users.Remove("Jane Doe");

Console.WriteLine(string.Join(", ", users));

users.Clear();

if (users.Count == 0)
{
    Console.WriteLine("The users dictionary is empty");
}

The example creates a new dictionary and modifies it using several built-in methods.

var users = new Dictionary<string, int>()
{
    { "John Doe", 41 },
    { "Jane Doe", 38 },
    { "Lucy Brown", 29 },
};

A new dictionary is created. The user names are the keys and the user ages are the values.

users["Paul Brown"] = 33;
users.Add("Thomas Pattison", 34);

We add two new pairs to the dictionary using dictionary access notation and the Add method.

Console.WriteLine(string.Join(", ", users));

We use the string Join method to display all elements in one shot.

users.Remove("Jane Doe");

A pair is removed with the Remove method. The parameter is the dictionary key.

users.Clear();

The dictionary is cleared with the Clear method.

$ dotnet run
[John Doe, 41], [Jane Doe, 38], [Lucy Brown, 29], [Paul Brown, 33], [Thomas Pattison, 34]
[John Doe, 41], [Lucy Brown, 29], [Paul Brown, 33], [Thomas Pattison, 34]
The users dictionary is empty

C# Dictionary ContainsKey and ContainsValue methods

The ContainsKey method determines whether the dictionary contains the specified key and the ContainsValue method determines whether the dictionary contains the specified value.

Program.cs
var domains = new Dictionary<string, string>
{
    {"sk", "Slovakia"},
    {"ru", "Russia"},
    {"de", "Germany"},
    {"no", "Norway"}
};

var key = "sk";

if (domains.ContainsKey(key))
{
    Console.WriteLine($"The {key} key is in the dictionary");
} else
{
    Console.WriteLine($"The {key} key is in not the dictionary");
}

var value = "Slovakia";

if (domains.ContainsValue(value))
{
    Console.WriteLine($"The {value} value is in the dictionary");
} else
{
    Console.WriteLine($"The {value} value is in not the dictionary");
}

In the example, we check if the "sk" key and "Slovakia" value are present in the dictionary.

$ dotnet run
The sk key is in the dictionary
The Slovakia value is in the dictionary

C# traverse dictionary

There are several ways to travers a C# dictionary.

Program.cs
var domains = new Dictionary<string, string>
{
    {"sk", "Slovakia"},
    {"ru", "Russia"},
    {"de", "Germany"},
    {"no", "Norway"}
};

foreach (var (key, value) in domains)
{
    Console.WriteLine($"{key}: {value}");
}

Console.WriteLine("**************************************");

foreach (var kvp in domains)
{
    Console.WriteLine($"{kvp.Key}: {kvp.Value}");
}

Console.WriteLine("**************************************");

// oldschool
foreach (KeyValuePair<string, string> entry in domains)
{
    Console.WriteLine($"{entry.Key}: {entry.Value}");
}

The example loops over a dictionary using foreach.

foreach (var (key, value) in domains)
{
    Console.WriteLine($"{key}: {value}");
}

In this foreach loop, we go through the dictionary by pairs. Each pair is decomposed into its key and value.

foreach (var kvp in domains)
{
    Console.WriteLine($"{kvp.Key}: {kvp.Value}");
}

In this case, we access the keys and values by their Key and Value properties.

// oldschool
foreach (KeyValuePair<string, string> entry in domains)
{
    Console.WriteLine($"{entry.Key}: {entry.Value}");
}

Finally, this is an older way of traversing a dictionary by pairs using KeyValuePair.

$ dotnet run
sk: Slovakia
ru: Russia
de: Germany
no: Norway
**************************************
sk: Slovakia
ru: Russia
de: Germany
no: Norway
**************************************
sk: Slovakia
ru: Russia
de: Germany
no: Norway

C# allows to loop over keys and values separetely.

Program.cs
var domains = new Dictionary<string, string>
{
    {"sk", "Slovakia"},
    {"ru", "Russia"},
    {"de", "Germany"},
    {"no", "Norway"}
};

Console.WriteLine("Keys:");

foreach (var val in domains.Keys)
{
    Console.WriteLine(val);
}

Console.WriteLine("\nValues:");

foreach (var val in domains.Values)
{
    Console.WriteLine(val);
}

The example prints all keys and all values of a dictionary in two foreach loops.

foreach (var val in domains.Keys)
{
    Console.WriteLine(val);
}

We use the Keys property to get all keys.

foreach (var val in domains.Values)
{
    Console.WriteLine(val);
}

We use the Values property to get all values.

$ dotnet run
Keys:
sk
ru
de
no

Values:
Slovakia
Russia
Germany
Norway

C# sort dictionary

We can use LINQ to sort dicionaries.

Program.cs
var users = new Dictionary<string, int>()
{
    { "John", 41 },
    { "Jane", 38 },
    { "Lucy", 29 },
    { "Paul", 24 }
};

var sortedUsersByValue = users.OrderBy(user => user.Value);

foreach (var user in sortedUsersByValue)
{
    Console.WriteLine($"{user.Key} is {user.Value} years old");
}

The example sorts the dictionary by user ages.

var sortedUsersByValue = users.OrderBy(user => user.Value);

The OrderBy method is used to sort the entries by their values.

$ dotnet run
Paul is 24 years old
Lucy is 29 years old
Jane is 38 years old
John is 41 years old

C# SortedDictionary

SortedDictionary represents a collection of key/value pairs that are sorted on the key.

Program.cs
var sortedUsers = new SortedDictionary<string, int>()
{
    { "John", 41 },
    { "Jane", 38 },
    { "Lucy", 29 },
    { "Paul", 24 }
};

foreach (var user in sortedUsers)
{
    Console.WriteLine($"{user.Key} is {user.Value} years old");
}

The example demonstrates the usage of the SortedDictionary.

$ dotnet run
Jane is 38 years old
John is 41 years old
Lucy is 29 years old
Paul is 24 years old

C# Dictionary of Lists

In the following example, we have a dictionary of lists.

Program.cs
var data = new Dictionary<int, List<int>>();

var vals1 = new List<int> { 1, 1, 1, 1, 1 };
var vals2 = new List<int> { 3, 3, 3, 3, 3 };
var vals3 = new List<int> { 5, 5, 5, 5, 5 };

data.Add(1, vals1);
data.Add(2, vals2);
data.Add(3, vals3);

var TotalSum = 0;

foreach (var (key, e) in data)
{
    var _sum = e.Sum();
    TotalSum += _sum;
    Console.WriteLine($"The sum of nested list is: {_sum}");
}

Console.WriteLine($"The total sum is: {TotalSum}");

We add three lists of integers into a dictionary. We compute a sum for each nested list and a final total sum.

$ dotnet run
The sum of nested list is: 5
The sum of nested list is: 15
The sum of nested list is: 25
The total sum is: 45

Source

Dictionary class - language reference

In this article we have worked with a C# Dictionary collection.

Author

My name is Jan Bodnar and I am a passionate programmer with many years of programming experience. I have been writing programming articles since 2007. So far, I have written over 1400 articles and 8 e-books. I have over eight years of experience in teaching programming.

List all C# tutorials.