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:

  1. 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.

  1. Add a key-value pair:
dictionary.Add(key, value);
  1. Accessing and modifying key-value pairs.
TValue value = dictionary[key]; // 获取指定键的值
dictionary[key] = newValue; // 修改指定键的值
  1. Check if the key exists:
bool containsKey = dictionary.ContainsKey(key);
  1. Remove key-value pair.
dictionary.Remove(key);
  1. Iterate the key-value pairs:
foreach (KeyValuePair<TKey, TValue> pair in dictionary)
{
    TKey key = pair.Key;
    TValue value = pair.Value;
    // 处理键值对
}
  1. 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.

bannerAds