Dictionary in C# is a collection that stores key-value pairs, where each key is unique, and it is associated with a value. It’s part of the System.Collections.Generic namespace, and it provides fast lookups for data.
Key Points of Dictionary
1. Each Key in dictionary is unique, It can not be duplicate. If you try to add a duplicate key, it will throw an exception.
2. It uses a hash-based implementation, which generally provides fast access to values when searching by key.
3. The type of key and value can be defined by the user, allowing you to store a wide range of data types.
Syntax:
Dictionary dictionary = new Dictionary();
TKey is the type of the key.
TValue is the type of the value.
Declaration and Initialization
You can initialize a dictionary with a collection of key-value pairs using an initializer:
Dictionary employees = new Dictionary
{
{ "John", 35 },
{ "Tom", 30 },
{ "Mark", 25 }
};
Add item into the Dictionary
Items can be added using the Add method, but it throws an exception if the key already exists.
employees.Add("Alan", 20); // This adds a new entry.
You can add in other way
employees["Alan"] = 20; // This adds a new entry.
If we add duplicate key then it will show error.
employees.Add("Tom", 30); // / This throws an ArgumentException because "Tom" already exists.
Access Dictionary Key’s Value
To access values, you use the key inside square brackets:
int AgeOfTom = employees["Tom"]; // Retrieves 30
Check the Dictionary Key is exists or not
You can check if a dictionary contains a certain key using ContainsKey:
if (employees.ContainsKey("Tom"))
{
Console.WriteLine("Tom exists in the dictionary.");
}
Remove Dictionary Key
To remove an entry by key, use the Remove method:
employees.Remove("Mark"); // Removes the key "Mark" from the dictionary.
Remove all keys from Dictionary
You can remove all keys from Dictionary through clear() method
employees.Clear(); // Removes all key-value pairs.
Iterating Over a Dictionary
You can loop through a dictionary using a foreach loop, which iterates over each KeyValuePair:
foreach (var employee in employees)
{
Console.WriteLine($"{employee.Key}: {employee.Value}");
}