C#中的Dictionary属于System.Collections.Generic命名空间下的泛型集合,它基于哈希表实现,存储的是键值对结构的数据,能够通过键快速定位到对应的值,查找效率远高于普通列表,是开发中处理关联数据的常用工具。

Dictionary的基础定义与初始化
使用Dictionary前需要先引入对应的命名空间,然后可以指定键和值的类型来定义实例,常见的初始化方式有两种,一种是先定义再添加元素,另一种是直接在初始化时赋值。
using System.Collections.Generic;
// 定义键为int类型,值为string类型的Dictionary
Dictionary<int, string> studentDict = new Dictionary<int, string>();
// 初始化时直接赋值
Dictionary<string, int> scoreDict = new Dictionary<string, int>
{
{"张三", 90},
{"李四", 85},
{"王五", 92}
};
Dictionary的核心操作
添加元素
添加元素可以使用Add方法,需要注意的是Dictionary的键必须唯一,如果添加重复的键会抛出ArgumentException异常。
Dictionary<string, string> cityDict = new Dictionary<string, string>();
// 添加键值对
cityDict.Add("BJ", "北京");
cityDict.Add("SH", "上海");
// 下面这行代码会抛出异常,因为键BJ已经存在
// cityDict.Add("BJ", "北京朝阳区");
查询元素
查询元素有两种常用方式,一种是直接通过键访问,如果键不存在会抛出KeyNotFoundException异常;另一种是使用TryGetValue方法,该方法会返回布尔值表示是否查询成功,避免异常抛出。
Dictionary<string, int> ageDict = new Dictionary<string, int>
{
{"小明", 18},
{"小红", 17}
};
// 方式1:直接通过键访问
int xiaoMingAge = ageDict["小明"];
Console.WriteLine(xiaoMingAge); // 输出18
// 方式2:使用TryGetValue查询
if (ageDict.TryGetValue("小红", out int xiaoHongAge))
{
Console.WriteLine(xiaoHongAge); // 输出17
}
else
{
Console.WriteLine("未找到对应键");
}
// 直接访问不存在的键会抛出异常
// int age = ageDict["小刚"]; // 抛出KeyNotFoundException
删除元素
删除元素可以使用Remove方法,该方法会返回布尔值,表示是否成功删除,如果键不存在则返回false,不会抛出异常。
Dictionary<int, string> idDict = new Dictionary<int, string>
{
{1, "商品A"},
{2, "商品B"},
{3, "商品C"}
};
// 删除键为2的元素
bool isRemoved = idDict.Remove(2);
Console.WriteLine(isRemoved); // 输出True
// 删除不存在的键
bool isRemoved2 = idDict.Remove(5);
Console.WriteLine(isRemoved2); // 输出False
遍历元素
遍历Dictionary可以遍历它的键值对集合,也可以分别遍历键集合和值集合,遍历键值对时可以同时拿到键和值的信息。
Dictionary<string, double> priceDict = new Dictionary<string, double>
{
{"苹果", 5.5},
{"香蕉", 3.8},
{"橙子", 4.2}
};
// 遍历键值对
Console.WriteLine("遍历所有商品及价格:");
foreach (KeyValuePair<string, double> item in priceDict)
{
Console.WriteLine($"商品:{item.Key},价格:{item.Value}");
}
// 遍历所有键
Console.WriteLine("所有商品名称:");
foreach (string key in priceDict.Keys)
{
Console.WriteLine(key);
}
// 遍历所有值
Console.WriteLine("所有商品价格:");
foreach (double value in priceDict.Values)
{
Console.WriteLine(value);
}
Dictionary的使用注意事项
- 键必须唯一,且如果键是自定义类型,需要保证该类型正确重写了
GetHashCode和Equals方法,否则可能导致哈希冲突或者查找异常。 - Dictionary本身不是线程安全的,如果需要在多线程场景下使用,建议使用
ConcurrentDictionary或者在操作外层加锁。 - 如果需要判断某个键是否存在,不要先捕获异常再处理,应该使用
ContainsKey方法,异常处理的性能远低于正常的条件判断。 - Dictionary的键值对顺序是不固定的,不要依赖它的遍历顺序来做业务逻辑,如果需要有序的键值对集合,可以使用
SortedDictionary。
常见使用场景示例
比如我们需要统计一段文本中每个字符出现的次数,就可以用Dictionary来快速实现:
string text = "hello world";
Dictionary<char, int> charCountDict = new Dictionary<char, int>();
foreach (char c in text)
{
if (charCountDict.ContainsKey(c))
{
charCountDict[c]++;
}
else
{
charCountDict.Add(c, 1);
}
}
// 输出统计结果
foreach (KeyValuePair<char, int> item in charCountDict)
{
Console.WriteLine($"字符'{item.Key}'出现次数:{item.Value}");
}
C#Dictionary键值对哈希表泛型集合修改时间:2026-06-17 23:00:35