How to Use a Dictionary in C# | TechBuzz

- Advertisement -

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:

- Advertisement -
1001, "Mia",
1002, "Oscar",
1003, "Birdie",
1004, "Bluey",
1005, "Leo",
1006, "Travis"

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.

  1. Create the dictionary. In this example, the key is an integer and the value for each record is a string.
    - Advertisement -
    Dictionary<int, string> pets = new Dictionary<int, string>();
  2. 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:
    using System.Collections.Generic;

How to Add Items to the Dictionary

You can add items to the dictionary during or after its initialization.

  1. You can add items while initializing the dictionary. To do so, add some values in curly brackets after the initial new Dictionary statement.
    - Advertisement -
    Dictionary<int, string> pets = new Dictionary<int, string>()

    1001, "Mia",
    1002, "Oscar",
    1003, "Birdie",
    1004, "Bluey",
    1005, "Leo",
    1006, "Travis"
  2. If you have already created the dictionary, you can use the dictionary’s built-in Add() method.
    pets.Add(1007, "Snowy");

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.

  1. Make sure you create the dictionary with the Pet object type specified for the value.
    Dictionary<int, Pet> petObjects = new Dictionary<int, Pet>();
  2. Create your pet object.
    Pet mia = new Pet(1001, "Mia", new DateTime(2010, 6, 29), 9.0,
    new DateTime(2022, 05, 02));
  3. Add the new pet object to the dictionary.
    petObjects.Add(1001, mia);

How to Access an Item in the Dictionary

You can access an item in the dictionary using the Key.

  1. 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[1001];

How to Iterate Over the Dictionary

You can use a foreach loop to iterate over a dictionary:

  1. 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.

  1. If you have simple object types in your dictionary, you can overwrite a value of a record directly.
    pets[1001] = "Maya";
  2. 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[1001] = bunny;
  3. 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[1001].name = "Maya";

How to Delete an Item in a Dictionary

You can choose to delete a single item or all items.

  1. 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.
  2. 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.

Gray laptop showing html code
3 Advanced Data Structures Every Programmer Should Know

Read Next

About The Author

Source link

- Advertisement -
I am admin of blog & I provide tech-related news. As a part of my hobby, I make content related to technology and gadgets reviews too. I love to be a content creator apart from it, I am a full-time employee in an MNC company and manage blogs systematically. You can mail me at [email protected]

More from author

Related posts


Latest posts

Xiaomi Mega Bundle: Redmi Note 11, Earbuds & 10 GB for less than €13/month | TechBuzz

Are you looking for a powerful smartphone including a tariff at a reasonable price? In the Curved Shop you can get the Xiaomi...

WWDC: macOS Alcatraz? | TechBuzz

The name macOS Alcatraz was, of course, just a joking name for Apple's next operating system. Nevertheless, in this issue we also speculated about...

Windows 11 version 22H2 – a new major update coming to us in the second half of the year | TechBuzz

Microsoft is currently working intensively on a new version of Windows known as 22H2 version and codenamed Sun Valley 2. This is the...

Want to stay up to date with the latest news?

We would love to hear from you! Please fill in your details and we will stay in touch. It's that simple!