Dictionary<TKey, TValue> Class

Namespace: System.Collections.Generic
Assembly: System.Private.CoreLib (in System.Private.CoreLib.dll)

Represents a collection of key/value pairs that are sorted by key. The keys in a Dictionary<TKey, TValue> must be unique and cannot be null.

Syntax

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

The Dictionary<TKey, TValue> type exposes the following members.

Members

Constructors

public Dictionary()

Initializes a new instance of the Dictionary<TKey, TValue> class that is empty, has the default initial capacity, and uses the default equality comparer for the type of the keys.

public Dictionary(int capacity)

Initializes a new instance of the Dictionary<TKey, TValue> class that is empty, has the specified initial capacity, and uses the default equality comparer for the type of the keys.

Parameters:

public Dictionary(IEqualityComparer<TKey> comparer)

Initializes a new instance of the Dictionary<TKey, TValue> class that is empty, has the default initial capacity, and uses the specified IEqualityComparer<TKey>.

Parameters:

public Dictionary(int capacity, IEqualityComparer<TKey> comparer)

Initializes a new instance of the Dictionary<TKey, TValue> class that is empty, has the specified initial capacity, and uses the specified IEqualityComparer<TKey>.

Parameters:

public Dictionary<TKey, TValue>(IDictionary<TKey, TValue> dictionary)

Initializes a new instance of the Dictionary<TKey, TValue> class by copying the elements from the specified IDictionary<TKey, TValue> and uses the default equality comparer for the type of the keys.

Parameters:

public Dictionary<TKey, TValue>(IDictionary<TKey, TValue> dictionary, IEqualityComparer<TKey> comparer)

Initializes a new instance of the Dictionary<TKey, TValue> class by copying the elements from the specified IDictionary<TKey, TValue> and uses the specified IEqualityComparer<TKey>.

Parameters:

Properties

public int Count { get; }

Gets the number of elements contained in the Dictionary<TKey, TValue>.

public TValue this[TKey key] { get; set; }

Gets or sets the element with the specified key.

Parameters:

public KeyCollection Keys { get; }

Gets an ICollection<TKey> that contains the keys in the Dictionary<TKey, TValue>.

public ValueCollection Values { get; }

Gets an ICollection<TValue> that contains the values in the Dictionary<TKey, TValue>.

Methods

public void Add(TKey key, TValue value)

Adds an element with the specified key and value to the dictionary.

Parameters:

Exceptions:

public void Clear()

Removes all keys and values from the Dictionary<TKey, TValue>.

public bool ContainsKey(TKey key)

Determines whether the Dictionary<TKey, TValue> contains an element with the specified key.

Parameters:

Returns:

true if the Dictionary<TKey, TValue> contains an element with the specified key; otherwise, false.

public bool Remove(TKey key)

Removes the element with the specified key from the Dictionary<TKey, TValue>.

Parameters:

Returns:

true if the element is successfully found and removed; otherwise, false. If the element is not found, no operation is performed.

public bool TryGetValue(TKey key, out TValue value)

Gets the value associated with the specified key.

Parameters:

Returns:

true if the Dictionary<TKey, TValue> contains an element with the specified key; otherwise, false.

Example

Creating and Using a Dictionary

The following example demonstrates how to create a Dictionary<TKey, TValue>, add elements, access elements, and remove elements.

using System;
using System.Collections.Generic;

public class DictionaryExample
{
    public static void Main(string[] args)
    {
        // Create a dictionary with string keys and int values.
        Dictionary<string, int> openWith =
            new Dictionary<string, int>();

        // Add elements to the dictionary.
        openWith.Add("txt", 1);
        openWith.Add("bmp", 2);
        openWith.Add("jpg", 3);
        openWith.Add("png", 4);

        // Add an element with a pre-existing key will throw an ArgumentException.
        try
        {
            openWith.Add("jpg", 5);
        }
        catch (ArgumentException)
        {
            Console.WriteLine("An element with the key 'jpg' already exists.");
        }

        // Access the value associated with a key.
        int what = openWith["txt"];
        Console.WriteLine("The value associated with 'txt' is: {0}", what);

        // Access a value that doesn't exist. Will throw KeyNotFoundException.
        try
        {
            what = openWith["doc"];
        }
        catch (KeyNotFoundException)
        {
            Console.WriteLine("Key 'doc' not found.");
        }

        // Use TryGetValue to safely access a value.
        int fileValue;
        if (openWith.TryGetValue("png", out fileValue))
        {
            Console.WriteLine("The value associated with 'png' is: {0}", fileValue);
        }
        else
        {
            Console.WriteLine("Key 'png' not found.");
        }

        if (openWith.TryGetValue("docx", out fileValue))
        {
            Console.WriteLine("The value associated with 'docx' is: {0}", fileValue);
        }
        else
        {
            Console.WriteLine("Key 'docx' not found.");
        }

        // Iterate through the dictionary.
        Console.WriteLine("\nIterating through the dictionary:");
        foreach (KeyValuePair<string, int> kvp in openWith)
        {
            Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
        }

        // Get the keys.
        Dictionary<string, int>.KeyCollection keyColl = openWith.Keys;

        // Get the values.
        Dictionary<string, int>.ValueCollection valColl = openWith.Values;

        // Remove an element from the dictionary.
        Console.WriteLine("\nRemoving 'bmp'...");
        openWith.Remove("bmp");

        // Check if the key exists after removal.
        if (!openWith.ContainsKey("bmp"))
        {
            Console.WriteLine("Key 'bmp' was successfully removed.");
        }

        Console.WriteLine("\nDictionary after removal:");
        foreach (KeyValuePair<string, int> kvp in openWith)
        {
            Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
        }

        // Clear the dictionary.
        openWith.Clear();
        Console.WriteLine("\nDictionary cleared. Count: {0}", openWith.Count);
    }
}