Dictionary<TKey, TValue> Class
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 Initializes a new instance of the Dictionary<TKey, TValue> class.
- Properties Gets a value indicating whether the dictionary is read-only.
- Methods Adds an element with the specified key and value to the dictionary.
Constructors
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.
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:
capacity: The number of elements that the new dictionary can initially accommodate.
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:
comparer: TheIEqualityComparer<TKey>implementation to use when comparing keys, or null to use the default equality comparer for the type of the keys.
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:
capacity: The number of elements that the new dictionary can initially accommodate.comparer: TheIEqualityComparer<TKey>implementation to use when comparing keys, or null to use the default equality comparer for the type of the keys.
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:
dictionary: TheIDictionary<TKey, TValue>whose elements are copied to the newDictionary<TKey, TValue>.
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:
dictionary: TheIDictionary<TKey, TValue>whose elements are copied to the newDictionary<TKey, TValue>.comparer: TheIEqualityComparer<TKey>implementation to use when comparing keys, or null to use the default equality comparer for the type of the keys.
Properties
Gets the number of elements contained in the Dictionary<TKey, TValue>.
Gets or sets the element with the specified key.
Parameters:
key: The key of the element to get or set.
Gets an ICollection<TKey> that contains the keys in the Dictionary<TKey, TValue>.
Gets an ICollection<TValue> that contains the values in the Dictionary<TKey, TValue>.
Methods
Adds an element with the specified key and value to the dictionary.
Parameters:
key: The object to use as the key of the element to add.value: The object to use as the value of the element to add.
Exceptions:
ArgumentNullException:keyis null.ArgumentException: An element with the same key already exists in theDictionary<TKey, TValue>.
Removes all keys and values from the Dictionary<TKey, TValue>.
Determines whether the Dictionary<TKey, TValue> contains an element with the specified key.
Parameters:
key: The key to locate in theDictionary<TKey, TValue>.
Returns:
true if the Dictionary<TKey, TValue> contains an element with the specified key; otherwise, false.
Removes the element with the specified key from the Dictionary<TKey, TValue>.
Parameters:
key: The key of the element to remove.
Returns:
true if the element is successfully found and removed; otherwise, false. If the element is not found, no operation is performed.
Gets the value associated with the specified key.
Parameters:
key: The key of the value to get.value: When this method returns, contains the value associated with the specified key, if the key is found; otherwise, the default value for the type of thevalueparameter. This parameter is passed uninitialized.
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);
}
}