c#

c# dictionary的用法是什么

小亿
84
2023-12-28 02:48:19
栏目: 编程语言

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

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

  1. 创建Dictionary对象:
Dictionary<TKey, TValue> dictionary = new Dictionary<TKey, TValue>();
  1. 添加键值对:
dictionary.Add(key, value);

或者使用索引器:

dictionary[key] = value;
  1. 获取值:
TValue value = dictionary[key];
  1. 检查是否包含指定的键:
bool containsKey = dictionary.ContainsKey(key);
  1. 获取所有的键或值:
ICollection<TKey> keys = dictionary.Keys;
ICollection<TValue> values = dictionary.Values;
  1. 遍历字典:
foreach (KeyValuePair<TKey, TValue> pair in dictionary)
{
    TKey key = pair.Key;
    TValue value = pair.Value;
    // 进行操作
}
  1. 移除键值对:
bool removed = dictionary.Remove(key);
  1. 清空字典:
dictionary.Clear();

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

0
看了该问题的人还看了