Documentation > .NET > APIs > System > System.Collections > System.Collections.Generic

Dictionary<TKey, TValue> Class

Namespace: System.Collections.Generic

Assembly: mscorlib (in mscorlib.dll)

Summary: Represents a collection of keys and values that are associated with each other and that are accessed through a key. The order in which the items are inserted into the dictionary is not guaranteed.

Generic Type Parameters:

  • TKey: The type of the keys in the dictionary.
  • TValue: The type of the values in the dictionary.

Syntax

public class Dictionary<TKey, TValue> : IDictionary<TKey, TValue>, ICollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>, IDictionary, ICollection, IEnumerable
            

Remarks

A Dictionary<TKey, TValue> is a generic collection that stores key-value pairs. It is highly efficient for lookup operations because it uses a hash table internally. Each element in the dictionary is a KeyValuePair<TKey, TValue> structure.

The TKey must be unique. If you attempt to add an element with a key that already exists, an exception will be thrown. The TKey must also be comparable. The Dictionary<TKey, TValue> uses the default equality comparer for the specified type, unless you provide a custom comparer.

Examples

The following C# code example demonstrates how to create, populate, and iterate over a Dictionary<TKey, TValue>.

using System;
using System.Collections.Generic;

public class Example
{
    public static void Main()
    {
        // Create a dictionary where the key is a string and the value is an int.
        Dictionary<string, int> ageDictionary = new Dictionary<string, int>();

        // Add key-value pairs to the dictionary.
        ageDictionary.Add("Alice", 30);
        ageDictionary.Add("Bob", 25);
        ageDictionary.Add("Charlie", 35);

        // Access values by key.
        Console.WriteLine($"Alice's age is: {ageDictionary["Alice"]}");

        // Check if a key exists.
        if (ageDictionary.ContainsKey("Bob"))
        {
            Console.WriteLine("Bob is in the dictionary.");
        }

        // Iterate over the dictionary.
        Console.WriteLine("\nDictionary contents:");
        foreach (KeyValuePair<string, int> kvp in ageDictionary)
        {
            Console.WriteLine($"Key: {kvp.Key}, Value: {kvp.Value}");
        }

        // Remove an element.
        ageDictionary.Remove("Charlie");
        Console.WriteLine("\nAfter removing Charlie:");
        foreach (KeyValuePair<string, int> kvp in ageDictionary)
        {
            Console.WriteLine($"Key: {kvp.Key}, Value: {kvp.Value}");
        }
    }
}

Methods

Public Methods

Properties

Public Properties