Working with Dictionaries in C#: The Dictionary Class for Key-Value Pair Storage
This tutorial explores C#'s `Dictionary` class, a key-value pair collection implemented using a hash table. Learn how to create dictionaries, add elements, access values using keys, iterate through key-value pairs, and leverage the efficiency of dictionaries in your C# programs.
Working with Dictionaries in C#: The `Dictionary` Class
Introduction
The `Dictionary
Key Features of `Dictionary`
- Key-Value Pairs: Stores data as key-value pairs, where each key is associated with a single value.
- Unique Keys: Keys must be unique within the dictionary. Attempting to add a duplicate key will throw an exception.
- Fast Lookups: Uses a hash table for efficient retrieval of values based on their keys.
- Namespace: Located in `System.Collections.Generic`.
Example: Creating and Iterating Through a Dictionary
This example demonstrates creating a dictionary of strings (using integer keys), adding elements using the `Add()` method, and then iterating through the key-value pairs using a `foreach` loop and the `KeyValuePair` class.
Example: Dictionary Usage
using System;
using System.Collections.Generic;
public class DictionaryExample {
public static void Main(string[] args) {
Dictionary<string, string> names = new Dictionary<string, string>();
names.Add("1", "Sonoo");
names.Add("2", "Peter");
names.Add("3", "James");
names.Add("4", "Ratan");
names.Add("5", "Irfan");
foreach (KeyValuePair<string, string> kv in names) {
Console.WriteLine($"{kv.Key} {kv.Value}");
}
}
}
Example Output
1 Sonoo
2 Peter
3 James
4 Ratan
5 Irfan
Explanation
The code creates a dictionary where both keys and values are strings. The `foreach` loop iterates through each `KeyValuePair`, allowing access to both the key and its corresponding value.
Conclusion
The `Dictionary