C# Dictionary Generic Collection Tutorial

In this tutorial we learn about a complex data container in C# that stores elements by key/value pairing, called dictionaries.

We cover how to define and initialize a dictionary, access and modify dictionary elements with the indexer or loops, remove elements as well as how to check if an item exists in a dictionary.

What is a dictionary

A dictionary in C# is similar to an actual dictionary, which has a word and its meaning. In the same way, a C# dictionary has a collection of keys and values, where the key is the word, and the value is its meaning.

The dictionary namespace

Dictionaries are defined in the System.Collections.Generic namespace, so before we can use them, we must specify the namespace at the top of the document.

Example:
using System;
using System.Collections.Generic;

Now dictionaries will be available to use for use.

How to define a dictionary

We create a dictionary with the new keyword, which will instantiate a new dictionary object. A dictionary is also a generic type, as indicated by the angle brackets.

We need to give the dictionary two properties, a key and a value that will correspond to the key.

Syntax:
Dictionary<keyType, valueType> identifier = new Dictionary<keyType, valueType>();
Example:
using System.Collections.Generic;

namespace Dictionaries
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<int, string> message = new Dictionary<int, string>();
        }

    }
}

In the example above, we specify the key as an integer and the value as a string.

Think of an array or list where we have an integer index. A dictionary is the same, except that we can specify the index ourselves.

How to initialize a dictionary with values

If we know ahead of time which key-value pairs we want inside the dictionary, we can use initialization syntax to populate the dictionary with values when it’s defined.

Initialization syntax for a dictionary is an added code block. Within the code block, we specify our keys and values, separated by a comma, inside a set of open and close curly braces.

Each set of key/value pairs are also separated by a comma.

Syntax:
Dictionary<keyType, valueType> identifier = new Dictionary<keyType, valueType>()
{
    { key1, value1 },
    { key2, value2 }
};

The dictionary’s code block is terminated with a semicolon.

Example:
using System.Collections.Generic;

namespace Dictionaries
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<int, string> message = new Dictionary<int, string>()
            {
                { 1, "Hello" },
                { 2, "World" }
            };
        }

    }
}

In the example above, we initialize a new dictionary with two key/value sets. The word “Hello” that will correspond to the key 1, and the word “World” that will correspond to the key 2.

How to access a single element in a dictionary with the indexer

To access an element in a dictionary, we specify the key that corresponds to the value we want between open and close square brackets.

Syntax:
 indentifier[key];
Example:
using System;
using System.Collections.Generic;

namespace Dictionaries
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<int, string> message = new Dictionary<int, string>()
            {
                { 1, "Hello" },
                { 2, "World" }
            };

            Console.WriteLine(message[1] + " " + message[2]);
            Console.ReadLine();
        }

    }
}

If we’re not sure about the key/value pair, we can use the TryGetValue() function.

The TryGetValue() function will return false if it can’t find the key, instead returning of an exception (error).

Syntax:
identifier.TryGetValue(key, out value);
Example:
using System;
using System.Collections.Generic;

namespace Dictionaries
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<int, string> message = new Dictionary<int, string>()
            {
                { 1, "Hello" },
                { 2, "World" }
            };

            string result;

            if (message.TryGetValue(3, out result))
                Console.WriteLine(result);
            else
                Console.WriteLine("Key does not exist");

            Console.ReadLine();
        }

    }
}

In the example above, we try to access the value at key number 3, which doesn’t exist.

If the key is found, its value will be stored in the out variable result, otherwise it will output a useful error message for us.

How to access multiple elements in a dictionary with a loop

To access the multiple elements in a dictionary, we use a loop. Because we may not know how many elements a dictionary has, the easiest is to just use a foreach loop.

Syntax:
foreach (KeyValuePair<int, string> element in dictionaryIdentifier)
{
    // element.Key
    // element.Value
}

For the element type, we use the same two types we used when defining the dictionary: KeyValuePair

To access the keys and values we use the properties Key and Value with dot notation. For example, element.Key or element.Value.

Example:
using System;
using System.Collections.Generic;

namespace Dictionaries
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<int, string> message = new Dictionary<int, string>()
            {
                { 1, "Hello" },
                { 2, "World" }
            };

            foreach (KeyValuePair<int, string> i in message)
                Console.WriteLine("Key: {0}, Value: {1}", i.Key, i.Value);

            Console.ReadLine();
        }

    }
}

In the example above, we loop through our dictionary in a foreach loop. For the loop’s temporary variable we use i, after which we can access the dictionary keys and values with i.Key and i.Value.

How to check if an element exists in a dictionary

We can check if a key or a key-value pair exists by using the ContainsKey() and ContainsValue() functions.

To check if a key exists, we use the ContainsKey() function.

Syntax:
dictionaryIdentifier.ContainsKey(keyValue);
Example:
using System;
using System.Collections.Generic;

namespace Dictionaries
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<int, string> message = new Dictionary<int, string>()
            {
                { 1, "Hello" },
                { 2, "World" }
            };

            Console.WriteLine(message.ContainsKey(1));

            Console.ReadLine();
        }

    }
}

In the example above, we check if the dictionary contains the key 1. The dictionary does contain the key 1, so the function returns true.

To check if a value exists, we use the ContainsValue() function.

Syntax:
dictionaryIdentifier.ContainsValue(value);
Example:
using System;
using System.Collections.Generic;

namespace Dictionaries
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<int, string> message = new Dictionary<int, string>()
            {
                { 1, "Hello" },
                { 2, "World" }
            };

            Console.WriteLine(message.ContainsValue("Hello"));

            Console.ReadLine();
        }

    }
}

In the example above, we check if the dictionary contains the value “Hello”. The function returns true if the dictionary contains the value.

How to remove elements from a dictionary

To remove an element from a dictionary, we use the Remove() function.

Syntax:
dictionaryIdentifier.Remove(key);
Example:
using System;
using System.Collections.Generic;

namespace Dictionaries
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<int, string> message = new Dictionary<int, string>()
            {
                { 1, "Hello" },
                { 2, "there" },
                { 3, "World" }
            };

            message.Remove(2);

            foreach (KeyValuePair<int, string> i in message)
                Console.WriteLine("Key: {0}, Value: {1}", i.Key, i.Value);

            Console.ReadLine();
        }

    }
}

In the example above, we remove the element with the key 2. The word “there” has been removed so when we print the dictionary to the console, it only shows “Hello” and “World”.

Summary: Points to remember

  • A dictionary is a complex generic data container, and is used to store elements as custom key/value pairs.
  • A dictionary requires us to specify the key and value types within angle brackets when it’s being defined or instantiated.
  • Dictionary items can be accessed via the indexer or loops and we must specify the custom index of the value we want.
  • We can check if a key or value exists in a dictionary with the ContainsKey() and ContainsValue() functions respectively.