In C#, Dictionary<TKey, TValue>
is a generic collection class that represents a collection of key-value pairs. It provides fast lookup and retrieval of values based on their associated keys. The TKey
type parameter specifies the type of the keys, while the TValue
type parameter specifies the type of the values.
Here’s an example of how to use Dictionary<TKey, TValue>
in C#:
// Create a new dictionary Dictionary<string, int> myDictionary = new Dictionary<string, int>(); // Add key-value pairs to the dictionary myDictionary.Add("apple", 5); myDictionary.Add("banana", 3); myDictionary.Add("orange", 8); // Access values by their keys int appleCount = myDictionary["apple"]; // Returns 5 int orangeCount = myDictionary["orange"]; // Returns 8 // Update the value associated with a key myDictionary["banana"] = 10; // Check if a key exists in the dictionary bool containsKey = myDictionary.ContainsKey("apple"); // Returns true // Iterate over the key-value pairs in the dictionary foreach (KeyValuePair<string, int> kvp in myDictionary) { Console.WriteLine($"Key: {kvp.Key}, Value: {kvp.Value}"); } // Remove a key-value pair from the dictionary bool removed = myDictionary.Remove("orange"); // Returns true // Clear all key-value pairs from the dictionary myDictionary.Clear();
The Dictionary<TKey, TValue>
class provides efficient lookup operations using hash codes, making it suitable for scenarios where fast access to values based on keys is required. It also offers methods for adding, removing, and updating key-value pairs, as well as other useful methods for working with dictionaries.