A Collection of Chat logs between AI and Human

A Tutorial about C# Dictionaries



In C#, a Dictionary<TKey, TValue> is a collection of keys and values. It is part of the System.Collections.Generic namespace. A dictionary allows you to store and retrieve values based on a key. Each key must be unique within a dictionary.

Here’s a step-by-step explanation of how to work with a Dictionary<string, int> in C#:


To declare a dictionary that uses strings as keys and integers as values, you would write:

Dictionary<string, int> artworkSequences = new Dictionary<string, int>();

Adding Items:

To add an item to the dictionary, use the Add method, specifying the key and value:

artworkSequences.Add("Artwork1", 1);

Here, "Artwork1" is the key, and 1 is the value associated with that key.

Retrieving Items:

To retrieve an item, you use the key inside square brackets:

int sequence = artworkSequences["Artwork1"];

This would set sequence to 1 since that’s the value associated with "Artwork1".

Checking for a Key:

Before retrieving a value, it’s a good practice to check if the key exists using the ContainsKey method:

if (artworkSequences.ContainsKey("Artwork1"))
    int sequence = artworkSequences["Artwork1"];

Updating Items:

To update the value associated with a key, you can simply assign a new value to that key:

artworkSequences["Artwork1"] = 2;

Now the value for "Artwork1" is 2.

Removing Items:

To remove an item, use the Remove method:


Now "Artwork1" and its associated value are no longer in the dictionary.

Iterating Over Items:

You can loop over the dictionary using a foreach loop:

foreach (KeyValuePair<string, int> kvp in artworkSequences)
    Console.WriteLine($"Key = {kvp.Key}, Value = {kvp.Value}");
    // string key = kvp.Key;
    //int value = kvp.Value;
    // Do something with key and value

This will print out each key-value pair in the dictionary.

Count Property:

To get the number of items in the dictionary, use the Count property:

int count = artworkSequences.Count;

Clearing the Dictionary:

To remove all items from the dictionary, use the Clear method:


Now artworkSequences is empty.

Dictionaries are powerful data structures that are ideal when you need fast lookups, updates, and deletions of pairs of associated data. They are implemented as hash tables, so key lookups are very efficient, typically close to O(1) complexity. However, they do not maintain the order of the elements. If you need a collection that maintains order, you might consider using SortedDictionary<TKey, TValue> or OrderedDictionary.

Post Author


  • Sakthi Sri

    senthil@trilliardbytes.com Sri Sakthi