How is a c# dictionary used?
In C#, a Dictionary is a collection of key-value pairs that allows access and manipulation of values through keys. It is a generic type that can store keys and values of any type.
Here are some common uses of the dictionary.
- Create a Dictionary object:
Dictionary<TKey, TValue> dictionary = new Dictionary<TKey, TValue>();
- Add a key-value pair:
dictionary.Add(key, value);
Alternatively, you could use an indexer.
dictionary[key] = value;
- Get value:
TValue value = dictionary[key];
- Check if it contains a specified key:
bool containsKey = dictionary.ContainsKey(key);
- Get all keys or values.
ICollection<TKey> keys = dictionary.Keys;
ICollection<TValue> values = dictionary.Values;
- Iterating through a dictionary:
foreach (KeyValuePair<TKey, TValue> pair in dictionary)
{
TKey key = pair.Key;
TValue value = pair.Value;
// 进行操作
}
- Remove key-value pair:
bool removed = dictionary.Remove(key);
- clear the dictionary
dictionary.Clear();
A Dictionary is an efficient data structure that allows for quick searching and manipulation of key-value pairs. It is widely used in many scenarios such as caching and indexing.