In this article [Show more]
Dictionary Methods in C#
In C#, the Dictionary<TKey, TValue> class is a versatile collection that offers a variety of methods for efficiently managing key-value pairs. Understanding these methods will help you utilize dictionaries effectively for different programming tasks. This article provides an overview of key methods available in Dictionary<TKey, TValue> and how to use them with practical examples.
Common Methods of Dictionary<TKey, TValue>
Adding Elements
- Add(key, value): Adds a new key-value pair to the dictionary.
using System;
using System.Collections.Generic;
public class DictionaryAddExample
{
public static void Main()
{
// Create a dictionary and add key-value pairs
Dictionary<string, int> scores = new Dictionary<string, int>();
scores.Add("Alice", 90);
scores.Add("Bob", 85);
scores.Add("Charlie", 95);
// Print the scores
Console.WriteLine("Initial scores:");
foreach (KeyValuePair<string, int> kvp in scores)
{
Console.WriteLine($"{kvp.Key}: {kvp.Value}");
}
}
}
Retrieving Values
- Indexer (dictionary[key]): Retrieves the value associated with a key but throws an exception if the key is not found.
- TryGetValue(key, out value): Safely retrieves a value and returns true if successful; otherwise, returns false.
using System; using System.Collections.Generic; public class DictionaryRetrieveExample { public static void Main() { // Create a dictionary with some initial data Dictionary<string, int> ages = new Dictionary<string, int> { { "Alice", 28 }, { "Bob", 30 } }; // Using indexer to retrieve a value Console.WriteLine($"Bob's age: {ages["Bob"]}"); // Using TryGetValue to retrieve a value safely if (ages.TryGetValue("Alice", out int aliceAge)) { Console.WriteLine($"Alice's age: {aliceAge}"); } else { Console.WriteLine("Alice not found."); } // Check for a non-existent key if (!ages.TryGetValue("Charlie", out int charlieAge)) { Console.WriteLine("Charlie not found."); } } }
Checking and Removing Elements
- ContainsKey(key): Checks if a key is present in the dictionary.
- Remove(key): Removes a key-value pair based on the key.
using System;
using System.Collections.Generic;
public class DictionaryRemoveExample
{
public static void Main()
{
// Create a dictionary with initial data
Dictionary<string, string> employees = new Dictionary<string, string>
{
{ "E123", "John Doe" },
{ "E456", "Jane Smith" }
};
// Check if a specific employee ID exists
string targetID = "E123";
if (employees.ContainsKey(targetID))
{
Console.WriteLine($"Employee {targetID}: {employees[targetID]}");
}
// Remove an employee by ID
employees.Remove("E123");
// Confirm removal
if (!employees.ContainsKey("E123"))
{
Console.WriteLine("Employee E123 has been removed.");
}
}
}
Other Useful Methods
- Count: Returns the number of key-value pairs.
- Clear: Removes all key-value pairs from the dictionary.
- Keys/Values: Returns collections of keys or values.
Conclusion
Dictionary<TKey, TValue> methods offer powerful ways to manage key-value pairs in C#. By understanding and using these methods effectively, you can implement efficient and reliable collections tailored to your application needs.