Dictionaries in C#
Introduction to Dictionaries
A dictionary in C# is a collection of key-value pairs. It allows fast lookups, additions, and deletions based on keys. Dictionaries are implemented in the System.Collections.Generic
namespace and provide a flexible way to store data pairs.
Creating a Dictionary
To create a dictionary, you need to specify the types for the keys and values. Here's an example of creating a dictionary with string keys and integer values:
Dictionary<string, int> ages = new Dictionary<string, int>();
Adding Elements to a Dictionary
You can add elements to a dictionary using the Add
method, where you provide the key and value as parameters:
ages.Add("Alice", 30);
ages.Add("Bob", 25);
Accessing Elements in a Dictionary
You can access elements in a dictionary by using their keys. If the key exists, it will return the value associated with that key:
int aliceAge = ages["Alice"];
30
Removing Elements from a Dictionary
You can remove elements from a dictionary using the Remove
method, where you specify the key of the element you want to remove:
ages.Remove("Bob");
Checking for Key Existence
Before accessing a key, you might want to check if it exists in the dictionary to avoid exceptions. You can use the ContainsKey
method for this:
if (ages.ContainsKey("Alice"))
{
int aliceAge = ages["Alice"];
}
Iterating Over a Dictionary
You can iterate over a dictionary using a foreach
loop to access each key-value pair:
foreach (KeyValuePair<string, int> kvp in ages)
{
Console.WriteLine("Key: {0}, Value: {1}", kvp.Key, kvp.Value);
}
Key: Alice, Value: 30
Updating Values in a Dictionary
You can update the value associated with a specific key by simply assigning a new value to that key:
ages["Alice"] = 31;
Dictionary Methods
Dictionaries provide several useful methods for manipulating their contents:
Count
- Gets the number of key-value pairs in the dictionary.Clear
- Removes all elements from the dictionary.TryGetValue
- Tries to get the value associated with a specific key, and returns a bool indicating success or failure.
int count = ages.Count;
ages.Clear();
int age;
if (ages.TryGetValue("Alice", out age))
{
Console.WriteLine("Alice's age is {0}", age);
}
else
{
Console.WriteLine("Alice not found");
}
Conclusion
Dictionaries in C# are a powerful and flexible way to store and manage key-value pairs. Understanding how to create, manipulate, and access dictionaries is essential for effective C# programming. Use the examples and methods provided above to start working with dictionaries in your own projects.