Generic Dictionary Implementation in C#
The Dictionary<TKey, TValue> class in the System.Collections.Generic namespace is a powerful collection designed for high-performance data retrieval using keys. It maps unique keys to specific values, providing an average time complexity of O(1) for lookups.
Core Characteristics
- Namespace: Requires
System.Collections.Generic. - Uniqueness: Every key within a dictionary must be unique; however, values can be duplicated.
- Type Safety: Both keys and values are strongly typed, supporting any data type from primitives like
intto complex custom objects. - Ordering: The collection does not guarantee a specific sort order for its elements.
Basic Usage
Initializing a dictionary and populating it with data is straightforward. Use the Add method or the collection initializer syntax.
// Creating a dictionary to map file extensions to application names
var appRegistry = new Dictionary<string, string>();
// Inserting elements
appRegistry.Add(".txt", "Notepad");
appRegistry.Add(".jpg", "Photos App");
appRegistry.Add(".pdf", "Adobe Reader");
Data Access and Modification
You can retrieve or update values using the indexer property. If the key exists, assigning a value to that key updates it; otherwise, it creates a new entry.
// Reading a value
string reader = appRegistry[".pdf"];
Console.WriteLine($"Handler: {reader}");
// Modifying a value
appRegistry[".pdf"] = "Edge Browser";
Iteration Techniques
You can iterate over keys, values, or the entire key-value pair collection.
// Iterating through Keys
foreach (string ext in appRegistry.Keys)
{
Console.WriteLine($"Extension: {ext}");
}
// Iterating through Values
foreach (string app in appRegistry.Values)
{
Console.WriteLine($"Application: {app}");
}
// Iterating through KeyValuePair objects
foreach (KeyValuePair<string, string> entry in appRegistry)
{
Console.WriteLine($"{entry.Key} is opened by {entry.Value}");
}
Safe Key Handling
Attempting to add a duplicate key or accessing a non-existent key via the indexer will throw an exception. Use ContainsKey or TryGetValue to perform safe operations.
// Preventing duplicate key errors
if (!appRegistry.ContainsKey(".txt"))
{
appRegistry.Add(".txt", "TextEdit");
}
// Using TryGetValue for safe retrieval
if (appRegistry.TryGetValue(".png", out string handler))
{
Console.WriteLine($"Found: {handler}");
}
else
{
Console.WriteLine("Extension not registered.");
}
// Removing an entry
appRegistry.Remove(".jpg");
Working with Custom Objects
Dictionaries are frequently used to store complex data structures indexed by a unique identifier.
public class UserProfile
{
public int Id { get; set; }
public string Username { get; set; }
}
// Mapping User IDs to UserProfile objects
var users = new Dictionary<int, UserProfile>();
for (int i = 1; i <= 3; i++)
{
users.Add(i, new UserProfile { Id = i * 10, Username = $"User_{i}" });
}
foreach (var entry in users)
{
Console.WriteLine($"ID: {entry.Key}, Name: {entry.Value.Username}");
}
Essential Properties and Methods
| Member | Description |
|---|---|
Count |
Returns the total number of key/value pairs. |
Keys |
Returns a collection containing all keys. |
Values |
Returns a collection containing all values. |
Add(K, V) |
Inserts a new entry; throws if the key exists. |
Clear() |
Removes all entries from the dictionary. |
ContainsKey(K) |
Checks if a specific key exists in the collection. |
ContainsValue(V) |
Checks if a specific value exists in the collection. |
Remove(K) |
Removes the entry associated with the specified key. |
TryGetValue(K, out V) |
Safely retrieves a value without throwing an exception. |