C# Dictionaries: Efficient Key-Value Pair Storage
Learn C# through interactive, bite-sized lessons. Build .NET applications with hands-on practice.
Start C# Journey →Dictionaries in C# are versatile collection types that store key-value pairs. They provide fast lookup and efficient data management for various programming scenarios.
What is a Dictionary?
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.
Creating and Using Dictionaries
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
Common Dictionary Operations
- Adding elements: Use
Add()method or indexer - Accessing values: Use indexer with the key
- Removing elements: Use
Remove()method - Checking for keys: Use
ContainsKey()method
Iterating Through a Dictionary
You can iterate through a Dictionary using a foreach loop:
foreach (KeyValuePair<string, int> kvp in ages)
{
Console.WriteLine($"{kvp.Key}: {kvp.Value}");
}
Dictionary Methods and Properties
| 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 |
Best Practices
- Use meaningful keys to enhance code readability
- Consider using
TryGetValue()to avoid exceptions when accessing non-existent keys - Utilize C# Generics to create type-safe dictionaries
Dictionary vs. Other Collections
Dictionaries offer faster lookup times compared to C# Lists for large datasets. However, they consume more memory. Choose based on your specific use case.
Advanced Dictionary Concepts
For more complex scenarios, consider exploring:
SortedDictionary<TKey, TValue>for sorted key-value pairsConcurrentDictionary<TKey, TValue>for thread-safe operations
Mastering dictionaries is crucial for efficient data management in C#. They are widely used in caching, data processing, and configuration storage scenarios.
Related Concepts
- C# HashSet for storing unique elements
- C# LINQ for querying dictionaries
- C# Lambda Expressions for concise key-value pair operations