You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#中如何从Dictionary中移除指定键

关于C# Dictionary移除键的疑问解答

嘿,你完全搞错啦!Dictionary<string, int>里的Remove()方法可不是只移除关联值——它会把整个键值对(键和对应的数值)一起从集合里删除。

举个例子,用你给出的代码来测试:

Dictionary<string, int> d = new Dictionary<string, int>();
d["dog"] = 1;
d["cat"] = 5;

// 调用Remove移除键"cat"
d.Remove("cat");

// 检查集合里是否还有"cat"这个键
bool hasCat = d.ContainsKey("cat"); // 这里会返回false
// 尝试获取"cat"的值也会抛出KeyNotFoundException

另外,Remove()方法还会返回一个布尔值,用来告诉你移除操作是否成功:如果集合里存在这个键,移除后返回true;如果键不存在,就返回false,方便你做后续判断:

bool removeSuccess = d.Remove("cat");
if (removeSuccess)
{
    Console.WriteLine("键\"cat\"已经被成功移除");
}
else
{
    Console.WriteLine("集合里找不到键\"cat\"");
}

简单来说,你担心的“只能移除值、不能移除键”的情况根本不存在,Remove()就是专门用来移除指定键及其对应值的方法,完全满足你的需求~

内容的提问来源于stack exchange,提问作者Angad Khurana

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 15:14:08