Ebooks

C# Dictionary tutorial

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
using System;
using System.Collections.Generic;

namespace Initializers
{
    class Program
    {
        static void Main(string[] args)
        {
            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

This is the output.

C# counting elements

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

Program.cs
using System;
using System.Collections.Generic;

namespace Counting
{
    class Program
    {
        static void Main(string[] args)
        {
            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

This is the output.

C# add and remove elements

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

Program.cs
using System;
using System.Collections.Generic;

namespace AddRemove
{
    class Program
    {
        static void Main(string[] args)
        {
            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

This is the output.

C# 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
using System;
using System.Collections.Generic;

namespace CheckElements
{
    class Program
    {
        static void Main(string[] args)
        {
            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

This is the output.

C# traverse dictionary

There are several ways to travers a C# dictionary.

Program.cs
using System;
using System.Collections.Generic;

namespace Traversing
{
    class Program
    {
        static void Main(string[] args)
        {
            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

This is the output.

C# allows to loop over keys and values separetely.

Program.cs
using System;
using System.Collections.Generic;

namespace Traversing2
{
    class Program
    {
        static void Main(string[] args)
        {
            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

This is the output.

C# sort dictionary

We can use LINQ to sort dicionaries.

Program.cs
using System;
using System.Collections.Generic;
using System.Linq;

namespace Sorting
{
    class Program
    {
        static void Main(string[] args)
        {
            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

The output is sorted by dictionary values.

C# SortedDictionary

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

Program.cs
using System;
using System.Collections.Generic;

namespace SortedDictEx
{
    class Program
    {
        static void Main(string[] args)
        {
            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

The output is sorted by dictionary keys.

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

You might also be interested in the following related tutorials: MySQL C# tutorial, Date and time in C#, Reading a web page in C#, or C# Winforms tutorial.