What is the method for using dictionaries in C#?
In C#, a dictionary is a collection of key-value pairs used to store and access data, similar to a physical dictionary where each entry has a unique key and corresponding value.
Here are some common methods for using dictionaries in C#:
- Create a dictionary:
Dictionarydictionary = new Dictionary (); - Add a key-value pair to the dictionary with the specified key and value.
- Retrieve the value:
TValue value = dictionary[key]; - Update the value: dictionary[key] = newValue;
- Check if the key exists:
bool exists = dictionary.ContainsKey(key); - Delete the key-value pair from the dictionary:
dictionary.Remove(key); - Iterate through the dictionary:
foreach(KeyValuePairpair in dictionary)
{
TKey key = pair.Key;
TValue value = pair.Value;
// Perform actions
} - Obtain the keys or values from the dictionary:
ICollection keys = dictionary.Keys;
ICollection values = dictionary.Values;
The above are some basic dictionary operation methods, more complex operations can be achieved by using other methods as needed.