c# dictionary的用法是什么

C#中的Dictionary是一种键值对集合,它允许通过键来访问和操作值。它是泛型类型,可以存储任意类型的键和值。

下面是一些Dictionary的常见用法:

创建Dictionary对象:

Dictionary<TKey, TValue> dictionary = new Dictionary<TKey, TValue>();

添加键值对:

dictionary.Add(key, value);

或者使用索引器:

dictionary[key] = value;

获取值:

TValue value = dictionary[key];

检查是否包含指定的键:

bool containsKey = dictionary.ContainsKey(key);

获取所有的键或值:

ICollection<TKey> keys = dictionary.Keys;
ICollection<TValue> values = dictionary.Values;

遍历字典:

foreach (KeyValuePair<TKey, TValue> pair in dictionary)
{
    TKey key = pair.Key;
    TValue value = pair.Value;
    // 进行操作
}

移除键值对:

bool removed = dictionary.Remove(key);

清空字典:

dictionary.Clear();

Dictionary是一种高效的数据结构,可以快速地查找和操作键值对。它在很多场景中都被广泛使用,例如缓存、索引等。

阅读剩余
THE END