How to Use a Dictionary in C#
A dictionary is a useful data structure that allows you to store key-value pairs. You can efficiently access a value from the dictionary using its key.
Dictionaries in C# support actions like removing a value or iterating over the entire set of values.
What Is a Dictionary in C#?
A C# dictionary is one of the most important data structures you can learn about. It’s a bit like the Java HashMap data structure. Its keys must be unique, but they can be of almost any type. A simple dictionary uses scalar values.
For example, this dataset has an ID of a pet as the key and the pet’s name as the value:
This structure allows you to access data using the particular key that references a record. For example, you can retrieve the record with the value Birdie by referencing it with the lookup key 1003.
How to Create a Dictionary
To create a dictionary, you need to specify the object type for both the key and value.
- Create the dictionary. In this example, the key is an integer and the value for each record is a string.
Dictionary<int, string> pets = new Dictionary<int, string>();
- You’ll need to use the System.Collections.Generic namespace which contains the Dictionary class. Ensure you do so at the top of your file:
How to Add Items to the Dictionary
You can add items to the dictionary during or after its initialization.
- You can add items while initializing the dictionary. To do so, add some values in curly brackets after the initial new Dictionary statement.
Dictionary<int, string> pets = new Dictionary<int, string>()
- If you have already created the dictionary, you can use the dictionary’s built-in Add() method.
You cannot add a value for a key that already exists. If you try to do so, you’ll get an ArgumentException.
You cannot use a null value as the key for an entry in a dictionary. However, you can store a null value in a dictionary.
How to Add Objects to the Dictionary
If you are using an object-oriented programming style, you likely have at least one class that you use to create objects with. Say you had a class that stored details about pets:
You can add objects created from this class to a dictionary.
- Make sure you create the dictionary with the Pet object type specified for the value.
Dictionary<int, Pet> petObjects = new Dictionary<int, Pet>();
- Create your pet object.
Pet mia = new Pet(1001, "Mia", new DateTime(2010, 6, 29), 9.0,
new DateTime(2022, 05, 02));
- Add the new pet object to the dictionary.
How to Access an Item in the Dictionary
You can access an item in the dictionary using the Key.
- Use the variable name for the dictionary, followed by the key around a pair of square brackets. This will return the object stored in that particular part of the dictionary.
var pet = petObjects;
How to Iterate Over the Dictionary
You can use a foreach loop to iterate over a dictionary:
- Use a foreach to iterate over each KeyValuePair in the dictionary. Assuming you called your iterator entry, you can access the key and value using entry.Key and entry.Value.
foreach (KeyValuePair<int, Pet> entry in petObjects)
How to Update an Item in a Dictionary
You can update an item by overwriting its value in the dictionary.
- If you have simple object types in your dictionary, you can overwrite a value of a record directly.
pets = "Maya";
- If you have added objects to your dictionary, you can overwrite a value to a completely new object.
Pet bunny = new Pet(1001, "Bunny", new DateTime(2021, 8, 1), 3.0, new DateTime(2021, 8, 4));
petObjects = bunny;
- If you have an object in the dictionary, you can also update a single property. You can overwrite the value of the property directly or use a setter.
petObjects.name = "Maya";
How to Delete an Item in a Dictionary
You can choose to delete a single item or all items.
- To delete a single item, use the dictionary’s Built-in Remove() method. Enter the key of the record you want to delete as an argument.
- To delete all items in the dictionary, use the dictionary’s Built-in Clear() method
Data Structures in C#
This tutorial covered how to create a dictionary in C#, and how to add items to the dictionary. Additionally, it has also covered how to update, delete, and iterate over the dictionary.
If you want to improve your data structure vocabulary, you can start exploring more advanced data structures. Some examples of these include the Fibonacci Heap, AVL Tree, or Red Black Tree.
3 Advanced Data Structures Every Programmer Should Know
About The Author
Sharlene Von Drehnen
(14 Articles Published)
Sharlene is a Tech Writer at MUO and also works full time in Software Development. She has a Bachelor of IT and has previous experience in Quality Assurance and University tutoring. Sharlene loves gaming and playing the piano.
via MUO – Feed https://ift.tt/AuV6K7k
May 14, 2022 at 04:03AM