C# Dictionary Guide: Key-Value Pairs Usage
A Dictionary in C# is a collection based on key-value pairs, used to store and manipulate pairs of keys and values. It is a type of generic collection class that can store keys and values of different types according to the requirements.
Here are some common uses of the dictionary:
- Create a Dictionary object:
Dictionary<TKey, TValue> dictionary = new Dictionary<TKey, TValue>();
TKey and TValue represent the types of keys and values you want to store.
- Add a key-value pair:
dictionary.Add(key, value);
- Accessing and modifying key-value pairs.
TValue value = dictionary[key]; // 获取指定键的值
dictionary[key] = newValue; // 修改指定键的值
- Check if the key exists:
bool containsKey = dictionary.ContainsKey(key);
- Remove key-value pair.
dictionary.Remove(key);
- Iterate the key-value pairs:
foreach (KeyValuePair<TKey, TValue> pair in dictionary)
{
TKey key = pair.Key;
TValue value = pair.Value;
// 处理键值对
}
- Collecting a set of keys or values:
ICollection<TKey> keys = dictionary.Keys; // 获取所有键的集合
ICollection<TValue> values = dictionary.Values; // 获取所有值的集合
These are some common uses of the Dictionary that also offers additional methods and properties to meet various needs.