Dictionary in C#
What is a Dictionary?
In C#, a Dictionary is a collection that stores key-value pairs. It provides fast lookup and retrieval of values based on their associated keys. Each key in a dictionary must be unique, and the keys are used to access their corresponding values efficiently.
Why do we need a Dictionary?
Dictionaries are useful when you need to store and retrieve data based on a specific identifier or key. They are often used in scenarios where you want to perform quick lookups, such as mapping names to phone numbers, storing configuration settings, or implementing caches.
What else can be used instead of a Dictionary?
In C#, you have several options besides a Dictionary to store key-value pairs, depending on your requirements:
- Hashtable: Similar to a Dictionary, but it is not type-safe and is generally less efficient.
- SortedDictionary: Maintains the key-value pairs in sorted order based on the keys.
- SortedList: Similar to SortedDictionary, but implemented as a list, which makes it more memory efficient for small collections.
Comparing Dictionary and other options:
- Hashtable: Dictionary is generally preferred over Hashtable because of its type-safety and improved performance.
- SortedDictionary and SortedList: These options are useful when you need to maintain the key-value pairs in sorted order, but they have slightly slower insert and retrieval times compared to Dictionary.
How to create a Dictionary in C# with an example:
Here’s an example of creating a Dictionary in C#:
Dictionary<string, int> studentGrades = new Dictionary<string, int>();
// Adding key-value pairs to the dictionary
studentGrades["John"] = 90;
studentGrades["Sarah"] = 85;
studentGrades["Michael"] = 92;
// Accessing values using keys
Console.WriteLine(studentGrades["Sarah"]); // Output: 85
// Checking if a key exists
if (studentGrades.ContainsKey("John"))
{
int grade = studentGrades["John"];
Console.WriteLine("John's grade: " + grade);
}
// Iterating over the key-value pairs
foreach (var pair in studentGrades)
{
Console.WriteLine(pair.Key + ": " + pair.Value);
}
Other features and examples of using Dictionary in C#:
a) Count property: You can use the Count property to get the number of key-value pairs in the dictionary.
Console.WriteLine("Number of students: " + studentGrades.Count);
b) TryGetValue method: The TryGetValue method allows you to retrieve a value from the dictionary while avoiding exceptions if the key is not found.
if (studentGrades.TryGetValue("Michael", out int michaelGrade))
{
Console.WriteLine("Michael's grade: " + michaelGrade);
}
c) Removing an item from the dictionary: You can remove a key-value pair from the dictionary using the Remove method.
studentGrades.Remove("John");
d) Adding an item to a Dictionary:
Dictionary<string, int> studentGrades = new Dictionary<string, int>();
// Adding key-value pairs to the dictionary
studentGrades["John"] = 90;
studentGrades["Sarah"] = 85;
studentGrades["Michael"] = 92;
In this example, we create a studentGrades
Dictionary with keys of type string
and values of type int
. We then add three key-value pairs to the dictionary using the square bracket notation.
e) Removing an item from a Dictionary:
Dictionary<string, int> studentGrades = new Dictionary<string, int>();
studentGrades["John"] = 90;
studentGrades["Sarah"] = 85;
studentGrades["Michael"] = 92;
// Removing an item from the dictionary
studentGrades.Remove("Sarah");
In this example, we remove the key-value pair with the key "Sarah"
from the studentGrades
dictionary using the Remove
method.
These examples demonstrate how to add and remove items from a Dictionary in C#. Remember that when adding items, the key must be unique, but the value can be duplicated. When removing items, you provide the key of the item you want to remove using the Remove
method.