The Dictionary<K, V> class in C# is part of the System.Collections.Generic namespace and provides a collection of key-value pairs.
Each key in a dictionary must be unique, and each key is associated with exactly one value.
Dictionaries are fast and efficient for retrieving values when you know the key, making them ideal for scenarios like lookup tables, mappings, and associative arrays.
In this tutorial, we’ll cover:
1. Creating a Dictionary<K, V>
To create a Dictionary<K, V>, include the System.Collections.Generic namespace. K is the type of the key, and V is the type of the value.
using System; using System.Collections.Generic; class Program { static void Main() { // Create an empty dictionary of string keys and int values Dictionary<string, int> ages = new Dictionary<string, int>(); // Create a dictionary with initial values Dictionary<string, string> capitals = new Dictionary<string, string> { { "USA", "Washington, D.C." }, { "France", "Paris" }, { "Japan", "Tokyo" } }; Console.WriteLine("Initial capitals dictionary:"); foreach (var item in capitals) { Console.WriteLine($"{item.Key}: {item.Value}"); } } }
Output:
Initial capitals dictionary: USA: Washington, D.C. France: Paris Japan: Tokyo
In this example:
- Dictionary<string, int> ages = new Dictionary<string, int>(); creates an empty dictionary with string keys and integer values.
- Dictionary<string, string> capitals initializes a dictionary with keys and values representing countries and their capitals.
2. Adding Elements to the Dictionary
You can add elements to a dictionary using the Add method or by using the indexer [].
using System; using System.Collections.Generic; class Program { static void Main() { Dictionary<string, int> ages = new Dictionary<string, int>(); // Adding elements with Add ages.Add("Alice", 30); ages.Add("Bob", 25); // Adding elements with indexer ages["Charlie"] = 35; Console.WriteLine("Ages dictionary:"); foreach (var item in ages) { Console.WriteLine($"{item.Key}: {item.Value}"); } } }
Output:
Ages dictionary: Alice: 30 Bob: 25 Charlie: 35
In this example:
- Add(“Alice”, 30) adds a key-value pair using Add.
- ages[“Charlie”] = 35; adds or updates a key-value pair using the indexer.
Note: Adding a duplicate key with Add will throw an ArgumentException.
3. Accessing and Modifying Elements
You can access and modify elements in a dictionary using the key as an index.
using System; using System.Collections.Generic; class Program { static void Main() { Dictionary<string, int> ages = new Dictionary<string, int> { { "Alice", 30 }, { "Bob", 25 } }; // Access elements Console.WriteLine("Alice's age: " + ages["Alice"]); // Modify an existing element ages["Alice"] = 31; Console.WriteLine("Updated Alice's age: " + ages["Alice"]); } }
Output:
Alice's age: 30 Updated Alice's age: 31
In this example:
- ages[“Alice”] accesses Alice’s age.
- ages[“Alice”] = 31; updates Alice’s age to 31.
Note: Attempting to access a non-existent key with [] will throw a KeyNotFoundException. Use TryGetValue to avoid this.
Using TryGetValue to Access Elements Safely
using System; using System.Collections.Generic; class Program { static void Main() { Dictionary<string, int> ages = new Dictionary<string, int> { { "Alice", 30 } }; if (ages.TryGetValue("Bob", out int age)) { Console.WriteLine("Bob's age: " + age); } else { Console.WriteLine("Bob is not in the dictionary."); } } }
Output:
Bob is not in the dictionary.
4. Removing Elements
You can remove elements from a dictionary using Remove or Clear.
using System; using System.Collections.Generic; class Program { static void Main() { Dictionary<string, int> ages = new Dictionary<string, int> { { "Alice", 30 }, { "Bob", 25 }, { "Charlie", 35 } }; // Remove a specific element by key ages.Remove("Bob"); // Clear all elements from the dictionary ages.Clear(); Console.WriteLine("Ages dictionary count after clearing: " + ages.Count); } }
Output:
Ages dictionary count after clearing: 0
In this example:
- Remove(“Bob”) removes the entry with the key “Bob”.
- Clear() removes all entries from the dictionary.
5. Checking for Keys and Values
You can check if a dictionary contains a specific key or value using ContainsKey and ContainsValue.
using System; using System.Collections.Generic; class Program { static void Main() { Dictionary<string, int> ages = new Dictionary<string, int> { { "Alice", 30 }, { "Bob", 25 } }; // Check if a key exists Console.WriteLine("Contains key 'Alice': " + ages.ContainsKey("Alice")); // Check if a value exists Console.WriteLine("Contains value 25: " + ages.ContainsValue(25)); } }
Output:
Contains key 'Alice': True Contains value 25: True
In this example:
- ContainsKey(“Alice”) checks if the key “Alice” exists.
- ContainsValue(25) checks if the value 25 exists.
6. Iterating Through a Dictionary
You can iterate through a dictionary using a foreach loop to access both keys and values.
using System; using System.Collections.Generic; class Program { static void Main() { Dictionary<string, string> capitals = new Dictionary<string, string> { { "USA", "Washington, D.C." }, { "France", "Paris" }, { "Japan", "Tokyo" } }; Console.WriteLine("Country capitals:"); foreach (KeyValuePair<string, string> item in capitals) { Console.WriteLine($"{item.Key}: {item.Value}"); } } }
Output:
Country capitals: USA: Washington, D.C. France: Paris Japan: Tokyo
In this example:
- The foreach loop iterates over each KeyValuePair<string, string>, allowing you to access both the key and value.
7. Practical Examples of Dictionary<K, V> in Real Scenarios
Example 1: Counting Word Occurrences in a String
You can use a dictionary to count how many times each word appears in a string.
using System; using System.Collections.Generic; class Program { static void Main() { string text = "hello world hello dictionary"; Dictionary<string, int> wordCount = new Dictionary<string, int>(); string[] words = text.Split(' '); foreach (string word in words) { if (wordCount.ContainsKey(word)) { wordCount[word]++; } else { wordCount[word] = 1; } } Console.WriteLine("Word occurrences:"); foreach (var item in wordCount) { Console.WriteLine($"{item.Key}: {item.Value}"); } } }
Output:
Word occurrences: hello: 2 world: 1 dictionary: 1
In this example:
- ContainsKey(word) checks if the word is already in the dictionary. If so, it increments the count; otherwise, it adds the word with a count of 1.
Example 2: Storing and Retrieving Student Grades
A dictionary can store students’ grades, using the student name as the key and the grade as the value.
using System; using System.Collections.Generic; class Program { static void Main() { Dictionary<string, double> grades = new Dictionary<string, double> { { "Alice", 85.5 }, { "Bob", 92.0 }, { "Charlie", 78.5 } }; // Display each student's grade Console.WriteLine("Student Grades:"); foreach (var item in grades) { Console.WriteLine($"{item.Key}: {item.Value}"); } // Retrieve a specific student's grade string student = "Alice"; if (grades.TryGetValue(student, out double grade)) { Console.WriteLine($"{student}'s grade: {grade}"); } else { Console.WriteLine($"{student} is not in the dictionary."); } } }
Output:
Student Grades: Alice: 85.5 Bob: 92.0 Charlie: 78.5 Alice's grade: 85.5
In this example:
- TryGetValue(student, out double grade) retrieves the grade for a specific student if it exists.
Summary
In this tutorial, we covered the Dictionary<K, V> class in C# and demonstrated its features:
- Creating a Dictionary<K, V>: Initializing dictionaries with or without initial values.
- Adding Elements: Using Add and indexer [] to add items.
- Accessing and Modifying Elements: Using keys to access and modify values, and TryGetValue for safe access.
- Removing Elements: Using Remove and Clear.
- Checking for Keys and Values: Using ContainsKey and ContainsValue.
- Iterating Through a Dictionary: Using foreach to access both keys and values.
- Practical Examples: Counting word occurrences and storing/retrieving student grades.
The Dictionary<K, V> class is an efficient and flexible collection type for managing key-value pairs, making it ideal for applications requiring fast lookups, such as storing user data, configurations, and more.