Unlock the Power of Dictionaries in C#

What is a Dictionary?

A dictionary is a generic collection that stores elements as key-value pairs, but unlike arrays or lists, these pairs are not stored in a specific order. Think of it like a phonebook, where each name (key) is associated with a phone number (value).

Creating a Dictionary

To create a dictionary in C#, you’ll need to use the System.Collections.Generic namespace. The basic syntax is:

Dictionary<dataType1, dataType2> dictionaryName = new Dictionary<dataType1, dataType2>();

For example, let’s create a dictionary called country with integer keys and string values:

Dictionary<int, string> country = new Dictionary<int, string>();

Basic Operations on Dictionaries

Dictionaries offer a range of operations that make them incredibly versatile. Here are some of the most common ones:

Add Elements

You can add elements to a dictionary using the Add() method. For instance:

Dictionary<string, string> mySongs = new Dictionary<string, string>();
mySongs.Add("Queen", "Break Free");
mySongs.Add("Free", "All right now");
mySongs.Add("Pink Floyd", "The Wall");

Alternatively, you can use the collection-initializer syntax to add elements without calling Add() explicitly:

Dictionary<string, string> mySongs = new Dictionary<string, string>()
{
{"Queen", "Break Free"},
{"Free", "All right now"},
{"Pink Floyd", "The Wall"}
};

Access Elements

To access a value in a dictionary, simply use its corresponding key:
“`
Dictionary student = new Dictionary()
{
{“Name”, “John Doe”},
{“Faculty”, “Engineering”}
};

string name = student[“Name”]; // returns “John Doe”
string faculty = student[“Faculty”]; // returns “Engineering”
“`

Iterate through Dictionaries

You can loop through each element of a dictionary using a foreach loop:
“`
Dictionary car = new Dictionary()
{
{“Model”, “Toyota”},
{“Year”, “2015”}
};

foreach (KeyValuePair entry in car)
{
Console.WriteLine($”Key = {entry.Key}, Value = {entry.Value}”);
}
“`

Change Elements

To modify a value in a dictionary, simply assign a new value to its corresponding key:
“`
Dictionary car = new Dictionary()
{
{“Model”, “Toyota”},
{“Year”, “2015”}
};

car[“Model”] = “Honda”; // changes the value of the “Model” key
“`

Remove Elements

To remove an element from a dictionary, use the Remove() method:
“`
Dictionary employee = new Dictionary()
{
{“Name”, “John Doe”},
{“Role”, “Manager”}
};

employee.Remove(“Role”); // removes the key-value pair “Role” : “Manager”

If you want to remove all elements from a dictionary, use the
Clear()` method.

Frequently Asked Questions

Did you know that you can also create a dictionary using the var keyword? For example:

var country = new Dictionary<int, string>();

This can be a convenient way to create a dictionary without explicitly specifying the type parameters.

Leave a Reply

Your email address will not be published. Required fields are marked *