Data Structures

C# Dictionaries

Working with Dictionaries

C# dictionaries use Dictionary<TKey TValue> for key-value pairs.

What is a C# Dictionary?

A C# Dictionary is a collection of key-value pairs that is optimized for fast lookups. It is part of the System.Collections.Generic namespace and is commonly used to store data that needs to be quickly retrieved based on a key. The dictionary uses a hash table to efficiently manage the keys.

Creating a Dictionary

To create a dictionary in C#, you need to specify the types for the keys and values. Here is a basic example:

Adding Elements to a Dictionary

Elements can be added to a dictionary using the Add method or by directly assigning a value to a key. Here's how you can add elements:

Accessing Dictionary Elements

You can access elements of a dictionary by their keys. If the key exists, it returns the corresponding value. Here's an example:

Removing Elements from a Dictionary

To remove an element from a dictionary, use the Remove method, which takes the key of the element you want to remove:

Checking for Key Existence

Before accessing a dictionary element, it's a good practice to check if the key exists using the ContainsKey method:

Iterating Through a Dictionary

You can iterate through all the key-value pairs in a dictionary using a foreach loop. This is useful when you want to process or display all elements:

Conclusion

C# dictionaries are a powerful and flexible way to manage collections of data by key. They offer fast lookups, additions, and deletions, making them ideal for scenarios where performance is critical. By understanding the basics of adding, accessing, and iterating over dictionary elements, you can effectively manage data in your C# applications.

Data Structures

Previous
Lists