Junior
What is a Dictionary in C#?
sobes.tech AI
Answer from AI
A Dictionary in C# is a collection that stores key-value pairs, where each key is unique and used for quick access to the corresponding value. It implements the interfaces IDictionary<TKey, TValue>, ICollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>, IEnumerable. It is based on a hash table.
Main characteristics:
- Unordered: The order of elements in the dictionary is not guaranteed and may change when adding/removing items.
- Performance: Add, remove, and key-based search operations have an average complexity of O(1) (in an ideal case, without hash collisions) and O(n) in the worst case.
- Key uniqueness: Each key must be unique in the dictionary. Attempting to add an element with an existing key will result in an exception.
Example usage:
// Creating a dictionary
Dictionary<string, int> students = new Dictionary<string, int>();
// Adding elements
students.Add("Ivanov", 5);
students["Petrov"] = 4; // Alternative way to add/update
// Checking for a key
if (students.ContainsKey("Ivanov"))
{
// Getting the value by key
int mark = students["Ivanov"]; // mark == 5
}
// Iterating over elements
foreach (KeyValuePair<string, int> student in students)
{
// student.Key - key, student.Value - value
Console.WriteLine($"{student.Key}: {student.Value}");
}
// Removing an element
students.Remove("Petrov");
Comparison with other collections:
| Collection | Main purpose | Index access | Key access | Key uniqueness | Ordered |
|---|---|---|---|---|---|
| List<T> | Sequence of elements | Yes | No | No | Yes |
| HashSet<T> | Unique set of elements | No | No | Yes | No |
| Dictionary<TKey, TValue> | Key-value pairs for quick search | No | Yes | Yes | No |