Initializes a new empty dictionary.
var dict = new Dictionary<string,int>();
Represents a collection of keys and values. A Dictionary
provides fast lookups by key. The type parameter TKey
represents the type of keys in the dictionary, and TValue
represents the type of values.
System.Collections.Generic
System.Collections.dll
public class Dictionary<TKey,TValue> : IDictionary<TKey,TValue>,
IDictionary,
IReadOnlyDictionary<TKey,TValue>,
ISerializable,
IDeserializationCallback
where TKey : notnull
Parameter | Description |
---|---|
TKey | The type of keys in the dictionary. Must be non‑nullable. |
TValue | The type of values in the dictionary. |
Initializes a new empty dictionary.
var dict = new Dictionary<string,int>();
Initializes a new dictionary with the specified initial capacity.
var dict = new Dictionary<string,int>(capacity: 100);
Initializes a new dictionary that contains elements copied from the specified dictionary.
var source = new Dictionary<string,int> { ["a"]=1, ["b"]=2 };
var dict = new Dictionary<string,int>(source);
Name | Type | Description |
---|---|---|
Count | int | Gets the number of key/value pairs contained in the dictionary. |
Keys | ICollection<TKey> | Gets a collection containing the keys in the dictionary. |
Values | ICollection<TValue> | Gets a collection containing the values in the dictionary. |
Item[TKey key] | TValue | Gets or sets the value associated with the specified key. |
Comparer | IEqualityComparer<TKey> | Gets the equality comparer used to compare keys. |
Adds the specified key and value to the dictionary.
dict.Add("apple", 5);
Determines whether the dictionary contains the specified key.
bool hasApple = dict.ContainsKey("apple");
Gets the value associated with the specified key, if present.
if (dict.TryGetValue("banana", out int qty))
{
Console.WriteLine($"Bananas: {qty}");
}
Removes the element with the specified key from the dictionary.
dict.Remove("apple");
Removes all keys and values from the dictionary.
dict.Clear();
Returns an enumerator that iterates through the dictionary.
foreach (var kvp in dict)
{
Console.WriteLine($"{kvp.Key}: {kvp.Value}");
}
// Create a dictionary of employee IDs and names
var employees = new Dictionary<int,string>
{
[101] = "Alice",
[102] = "Bob",
[103] = "Charlie"
};
// Update an entry
employees[102] = "Robert";
// Iterate
foreach (var (id, name) in employees)
{
Console.WriteLine($"ID {id}: {name}");
}
// Check existence
if (employees.TryGetValue(104, out var unknown))
{
Console.WriteLine(unknown);
}
else
{
Console.WriteLine("Employee 104 not found.");
}