Introduction to Dictionaries in C#
Introduction to Dictionaries
Hi, and welcome! Today, we'll explore Dictionaries, a data structure that organizes data as key-value pairs, much like a treasure box with unique labels for each compartment.
Imagine dozens of toys in a box. If each toy had a unique label (the key), you could directly select a toy (the value) using the label. No rummaging required — that's the power of Dictionaries! Today, we'll understand Dictionaries and learn how to implement them in C#.
Understanding Dictionaries in C#
Dictionaries are special data structures that use unique keys instead of indices. Think of them as arrays where the indices can be of any type, provided they are hashable and comparable.
C# implements Dictionaries through the Dictionary<TKey, TValue> class in the System.Collections.Generic namespace. They hold data in key-value pairs.
Let's create a Dictionary, functioning as a catalog for a library:
In this Dictionary, book1, book2, and book3 are keys, while the book titles serve as their respective values.
It's important to remember that the keys should be of a type that supports hashing and equality comparison. Examples include string, short, int, long, float, double, char, and bool. The values can be of any type.
Dictionary Operations: Accessing, Updating, and Removing Elements
Dictionary allows you to access, update, or remove elements:
-
Accessing Elements: You can retrieve a book's title using its key straightforwardly:
libraryCatalog["book1"]would return "A Tale of Two Cities." But what happens if you try to access a key that isn't present in theDictionary? This would throw aKeyNotFoundException. To avoid such exceptions, a safer way to access values is with theTryGetValue()method. This method takes two parameters: one for the key and one for the value. If the key exists in theDictionary, the method returns true and assigns the corresponding value to the value parameter. If the key does not exist, the method returns false. -
Adding or Updating Elements: When adding a new book, you can either use the
Add()method, or index notation:libraryCatalog.Add("book4", "Pride and Prejudice");orlibraryCatalog["book4"] = "Pride and Prejudice";. When updating an existing book's title in the catalog, you can only use index notation:libraryCatalog["book1"] = "The Tell-Tale Heart". -
Removing Elements: If
book1no longer exists in our library, you can remove it usinglibraryCatalog.Remove("book1").
