C# Dictionary
In C#, the Dictionary class is a generic collection that represents a collection of key-value pairs. It provides an efficient way to store and retrieve data based on unique keys.
Dictionary class in C#
Here are some important points to understand about the Dictionary class in C#:
Generic Collection:
The Dictionary class is part of the System.Collections.Generic namespace and is a generic collection. This means that you can specify the types of both keys and values when creating an instance of the dictionary.Key-Value Pairs:
Each entry in the dictionary consists of a unique key and an associated value. The key acts as an identifier or a lookup reference, while the value represents the data associated with that key.Unique Keys:
Dictionary keys must be unique within the dictionary. Attempting to add an entry with an existing key will result in an exception. This uniqueness ensures that each key is associated with a unique value.Fast Lookup:
One of the key advantages of using a dictionary is the fast lookup time. The dictionary internally uses a hash table to store the key-value pairs. This allows for efficient retrieval of values based on their keys, making it suitable for scenarios where quick access to values based on a specific key is required.Dynamic Size:
The dictionary has a dynamic size that can grow or shrink as elements are added or removed. The capacity is automatically adjusted to accommodate the number of elements present in the dictionary, ensuring efficient memory utilization.
Let's explore some examples to see how to work with the Dictionary class in C#:
Import the System.Collections.Generic namespace:
Create an instance of the Dictionary class and specify the types for keys and values:
In this example, we created a dictionary that uses strings as keys and integers as values. However, you can use any valid data type as the key and value types.
To add items to the dictionary, you can use the Add() method:
To retrieve values from the dictionary, you can use the indexer and provide the key:
You can also check if a key exists in the dictionary using the ContainsKey() method:
To remove an entry from the dictionary, you can use the Remove() method:
The Dictionary class provides other useful methods and properties, such as Count to get the number of entries in the dictionary, TryGetValue to retrieve a value safely without throwing an exception if the key is not found, and Keys and Values properties to retrieve all the keys or values in the dictionary.
Iterating over the dictionary
Here's an example of iterating over the dictionary:
This will display each key-value pair in the dictionary.
Conclusion
The Dictionary class in C# provides a powerful and efficient way to store and retrieve data based on unique keys. It is commonly used in various scenarios where fast lookup and key-value pair association are required, such as caching, data indexing, and more.