How to Use a Dictionary in C#

A dictionary is a useful data structure that allows you to store key-value pairs. You can effectively access a value from a dictionary using its key.

Dictionaries in C# support actions such as removing a value or iterating over an entire set of values.

What is a dictionary in C#?

The AC# dictionary is one of the most important data structures you can learn. It is somewhat similar to the Java HashMap data structure. Its keys must be unique, but they can be of almost any type. A simple dictionary using scalar values.

For example, this dataset has the pet’s ID as the key and the pet’s name as the value:

{1001, "Mia"},
{1002, "Oscar"},
{1003, "Birdie"},
{1004, "Bluey"},
{1005, "Leo"},
{1006, "Travis"}

This structure allows you to access data using a specific key that refers to a record. For example, you can retrieve a 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 an object type for both the key and the value.

MAKE A VIDEO OF THE DAY
  1. Create 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>();
  2. You will need to use System.Collections.Generic The namespace contains the Dictionary class. Make sure you do so at the top of your file:
    using System.Collections.Generic;

How to add entries to the dictionary

You can add entries to the dictionary during or after initialization.

  1. You can add entries during dictionary initialization. To do so, add some value in curly braces after the initial New Dictionary statement.
    Dictionary<int, string> pets = new Dictionary<int, string>()
    {
    {1001, "Mia"},
    {1002, "Oscar"},
    {1003, "Birdie"},
    {1004, "Bluey"},
    {1005, "Leo"},
    {1006, "Travis"}
    };
  2. If you’ve already created a dictionary, you can use the dictionary’s built-in Add() method.
    pets.Add(1007, "Snowy");


You cannot add a value to an already existing key. If you try to do so, you will get an ArgumentException.

You cannot use a invalid value as the key for a dictionary entry. However, you can store null values ​​in a dictionary.

How to add objects to a dictionary

If you’re using an object-oriented programming style, you probably have at least one class that you use to create objects. Suppose you have a class that stores details about pets:

You can add objects created from this class to the 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 a new pet object to the dictionary.
    petObjects.Add(1001, mia);


How to access a dictionary entry

You can access a dictionary entry with a 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];
    Console.WriteLine(pet.name);

How to Repeat a Dictionary

You can use a for every loop to iterate through the dictionary:

  1. Use foreach to iterate over each KeyValuePair in the dictionary. Let’s say you called your iterator entranceyou can access key and value using entry.Key and entry.Value.
    foreach (KeyValuePair<int, Pet> entry in petObjects)
    {
    Console.WriteLine(entry.Key);


    Console.WriteLine(entry.Value.name);
    }


How to update a dictionary entry

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 the value of the record directly.
    pets[1001] = "Maya";
  2. If you’ve already added objects to your dictionary, you can overwrite a value into an entirely 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 either override the attribute’s value directly or use a valuer.
    petObjects[1001].name = "Maya";
    petObjects[1001].setName("Maya");

How to delete an entry in the dictionary

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

  1. To remove an item, use the dictionary’s built-in Remove() method. Enter the key of the record you want to delete as an argument.
    petObjects.Remove(1002);
  2. To clear all entries in the dictionary, use the dictionary’s built-in Clear() method
    petObjects.Clear();

Data structure in C#

This tutorial covers how to create a dictionary in C# and how to add entries to the dictionary. In addition, it also covers how to update, delete, and iterate over the dictionary.

If you want to improve your data structures vocabulary, you can start exploring more advanced data structures. Some examples of them include Fibonacci Heap, AVL Tree or Red Black Tree.


Gray notebook showing html code

3 advanced data structures every programmer should know

Continue reading


About the author

https://www.makeuseof.com/c-sharp-dictionary-usage/ How to Use a Dictionary in C#

Sarah Ridley

USTimesPost.com is an automatic aggregator of the all world’s media. In each content, the hyperlink to the primary source is specified. All trademarks belong to their rightful owners, all materials to their authors. If you are the owner of the content and do not want us to publish your materials, please contact us by email – admin@ustimespost.com. The content will be deleted within 24 hours.

Related Articles

Back to top button