A dictionary is a useful data structure that allows you to store key-value pairs. You can efficiently access a value from the dictionary using its key.

Dictionaries in C# support actions like removing a value or iterating over the entire set of values.

What Is a Dictionary in C#?

A C# dictionary is one of the most important data structures you can learn about. It's a bit like the Java HashMap data structure. Its keys must be unique, but they can be of almost any type. A simple dictionary uses scalar values.

For example, this dataset has an ID of a pet as the key and the pet's name as the value:

        {1001, "Mia"},
{1002, "Oscar"},
{1003, "Birdie"},
{1004, "Bluey"},
{1005, "Leo"},
{1006, "Travis"}

This structure allows you to access data using the particular key that references a record. For example, you can retrieve the record with the value Birdie by referencing it with the lookup key 1003.

How to Create a Dictionary

To create a dictionary, you need to specify the object type for both the key and value.

  1. Create the dictionary. In this example, the key is an integer and the value for each record is a string.
            Dictionary<int, string> pets = new Dictionary<int, string>();
        
  2. You’ll need to use the System.Collections.Generic namespace which contains the Dictionary class. Ensure you do so at the top of your file:
            using System.Collections.Generic;

How to Add Items to the Dictionary

You can add items to the dictionary during or after its initialization.

  1. You can add items while initializing the dictionary. To do so, add some values in curly brackets after the initial new Dictionary statement.
            Dictionary<int, string> pets = new Dictionary<int, string>()
    {
        {1001, "Mia"},
        {1002, "Oscar"},
        {1003, "Birdie"},
        {1004, "Bluey"},
        {1005, "Leo"},
        {1006, "Travis"}
    };
  2. If you have already created the dictionary, you can use the dictionary's built-in Add() method.
            pets.Add(1007, "Snowy");
        

You cannot add a value for a key that already exists. If you try to do so, you’ll get an ArgumentException.

You cannot use a null value as the key for an entry in a dictionary. However, you can store a null value in a dictionary.

How to Add Objects to the Dictionary

If you are using an object-oriented programming style, you likely have at least one class that you use to create objects with. Say you had a class that stored details about pets:

Code for a simple Pet Class example

You can add objects created from this class to a dictionary.

  1. Make sure you create the dictionary with the Pet object type specified for the value.
            Dictionary<int, Pet> petObjects = new Dictionary<int, Pet>();
        
  2. Create your pet object.
            Pet mia = new Pet(1001, "Mia", new DateTime(2010, 6, 29), 9.0,
       new DateTime(2022, 05, 02));
  3. Add the new pet object to the dictionary.
            petObjects.Add(1001, mia);
        

How to Access an Item in the Dictionary

You can access an item in the dictionary using the Key.

  1. Use the variable name for the dictionary, followed by the key around a pair of square brackets. This will return the object stored in that particular part of the dictionary.
            var pet = petObjects[1001];
    Console.WriteLine(pet.name);

How to Iterate Over the Dictionary

You can use a foreach loop to iterate over a dictionary:

  1. Use a foreach to iterate over each KeyValuePair in the dictionary. Assuming you called your iterator entry, you can access the key and value using entry.Key and entry.Value.
            foreach (KeyValuePair<int, Pet> entry in petObjects)
    {
        // print the key
        Console.WriteLine(entry.Key);
      
        // print the name of the object for that record
        Console.WriteLine(entry.Value.name);
    }

How to Update an Item in a Dictionary

You can update an item by overwriting its value in the dictionary.

  1. If you have simple object types in your dictionary, you can overwrite a value of a record directly.
            pets[1001] = "Maya";
        
  2. If you have added objects to your dictionary, you can overwrite a value to a completely new object.
            Pet bunny = new Pet(1001, "Bunny", new DateTime(2021, 8, 1), 3.0, new DateTime(2021, 8, 4));
    petObjects[1001] = bunny;
  3. If you have an object in the dictionary, you can also update a single property. You can overwrite the value of the property directly or use a setter.
            petObjects[1001].name = "Maya";
    // OR
    petObjects[1001].setName("Maya");

How to Delete an Item in a Dictionary

You can choose to delete a single item or all items.

  1. To delete a single item, use the dictionary's Built-in Remove() method. Enter the key of the record you want to delete as an argument.
            petObjects.Remove(1002);
        
  2. To delete all items in the dictionary, use the dictionary's Built-in Clear() method
            petObjects.Clear();
        

Data Structures in C#

This tutorial covered how to create a dictionary in C#, and how to add items to the dictionary. Additionally, it has also covered how to update, delete, and iterate over the dictionary.

If you want to improve your data structure vocabulary, you can start exploring more advanced data structures. Some examples of these include the Fibonacci Heap, AVL Tree, or Red Black Tree.