Dictionaries in C# are versatile collection types that store key-value pairs. They provide fast lookup and efficient data management for various programming scenarios.
A Dictionary is a generic collection that stores key-value pairs. Each key must be unique within the collection. Dictionaries are part of the System.Collections.Generic
namespace.
To create a Dictionary, specify the types for both the key and value:
Dictionary<string, int> ages = new Dictionary<string, int>();
ages.Add("Alice", 30);
ages["Bob"] = 25;
int aliceAge = ages["Alice"]; // Retrieves 30
Add()
method or indexerRemove()
methodContainsKey()
methodYou can iterate through a Dictionary using a foreach loop:
foreach (KeyValuePair<string, int> kvp in ages)
{
Console.WriteLine($"{kvp.Key}: {kvp.Value}");
}
Method/Property | Description |
---|---|
Count |
Returns the number of key-value pairs |
Clear() |
Removes all key-value pairs |
TryGetValue() |
Attempts to get the value for a specified key |
TryGetValue()
to avoid exceptions when accessing non-existent keysDictionaries offer faster lookup times compared to C# Lists for large datasets. However, they consume more memory. Choose based on your specific use case.
For more complex scenarios, consider exploring:
SortedDictionary<TKey, TValue>
for sorted key-value pairsConcurrentDictionary<TKey, TValue>
for thread-safe operationsMastering dictionaries is crucial for efficient data management in C#. They are widely used in caching, data processing, and configuration storage scenarios.