在C#中,Dictionary
1. 创建并添加元素
使用 new Dictionary
Dictionary
ages.Add("张三", 25);
ages.Add("李四", 30);
ages.Add("王五", 28);
也可以在初始化时直接赋值:
var scores = new Dictionary
{
{ "语文", 89.5 },
{ "数学", 94.0 },
{ "英语", 87.0 }
};
2. 删除元素
使用 Remove(key) 方法根据键删除对应的键值对,返回 bool 值表示是否删除成功。
bool isRemoved = ages.Remove("李四");
if (isRemoved)
Console.WriteLine("删除成功");
else
Console.WriteLine("键不存在,删除失败");
还可以清空整个字典:
ages.Clear(); // 删除所有元素
3. 查询与访问元素
通过键直接访问值,但需确保键存在,否则会抛出异常。推荐使用 TryGetValue 安全获取值。
// 直接访问(可能抛出 KeyNotFoundException)
int age = ages["张三"];
// 推荐方式:安全获取
if (ages.TryGetValue("张三", out int foundAge))
Console.WriteLine($"年龄是: {foundAge}");
else
Console.WriteLine("未找到该姓名");
检查某个键或值是否存在:
bool hasKey = ages.ContainsKey("张三");
bool hasValue = ages.ContainsValue(25);
4. 遍历字典
使用 foreach 遍历所有键值对:
foreach (var kvp in scores)
{
Console.WriteLine($"{kvp.Key}: {kvp.Value}");
}
基本上就这些。Dictionary 的操作简单高效,注意避免重复添加相同键,以及使用 TryGetValue 防止异常。实际开发中很实用。
