.NET Framework Documentation

Dictionary<TKey, TValue> Class

System.Collections.Generic

Represents a collection of key/value pairs that are organized by key. Each key in the dictionary must be unique and cannot be null.

Summary

The Dictionary<TKey, TValue> class is a generic collection that stores elements as key/value pairs. It provides efficient lookup, insertion, and removal operations based on the key. The keys must be unique and non-null. The type of the keys and values can be specified when the dictionary is created.

Syntax


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

Namespace: System.Collections.Generic
Assembly: System.Private.CoreLib (in .NET Core/.NET 5+) or System.Collections (in .NET Framework)

Remarks

The Dictionary<TKey, TValue> uses a hash table to store the elements. This allows for average time complexity of O(1) for most operations, such as adding, retrieving, and removing elements.

If the number of elements in the dictionary is allowed to grow, the hash table grows automatically when new elements are added. If the collection size is known in advance, you can improve performance by initializing the Dictionary<TKey, TValue> with a capacity equal to the number of elements that are expected to be added.

The Dictionary<TKey, TValue> is not thread-safe. Multiple threads can read from and write to a Dictionary<TKey, TValue> concurrently. Special care must be taken by the programmer to ensure the thread safety of the application. For a thread-safe collection, see System.Collections.Concurrent.ConcurrentDictionary<TKey, TValue>.

Constructors

Methods

Properties

Examples

Creating and Populating a Dictionary

using System;
using System.Collections.Generic;

public class Example
{
    public static void Main()
    {
        // Create a dictionary with string keys and int values
        Dictionary<string, int> ages = new Dictionary<string, int>();

        // Add elements to the dictionary
        ages.Add("Alice", 30);
        ages.Add("Bob", 25);
        ages["Charlie"] = 35; // Another way to add or update

        // Accessing values
        Console.WriteLine($"Alice is {ages["Alice"]} years old.");

        // Checking if a key exists
        if (ages.ContainsKey("Bob"))
        {
            Console.WriteLine("Bob's age is found.");
        }

        // Iterating through the dictionary
        Console.WriteLine("\nAll entries:");
        foreach (KeyValuePair<string, int> kvp in ages)
        {
            Console.WriteLine($"Key: {kvp.Key}, Value: {kvp.Value}");
        }
    }
}
            
Using TryGetValue

using System;
using System.Collections.Generic;

public class Example
{
    public static void Main()
    {
        Dictionary<string, int> productPrices = new Dictionary<string, int>
        {
            { "Laptop", 1200 },
            { "Mouse", 25 },
            { "Keyboard", 75 }
        };

        int price;
        if (productPrices.TryGetValue("Mouse", out price))
        {
            Console.WriteLine($"The price of the Mouse is: ${price}");
        }
        else
        {
            Console.WriteLine("Mouse not found in the price list.");
        }

        if (productPrices.TryGetValue("Monitor", out price))
        {
            Console.WriteLine($"The price of the Monitor is: ${price}");
        }
        else
        {
            Console.WriteLine("Monitor not found in the price list.");
        }
    }
}