如何从c#中的字典中删除KEY

问题描述 投票:0回答:2

如上所述,我有一本名为 d 的字典。

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

现在,如果我想删除键“cat”,我不能使用Remove()方法,因为它只删除关联的相应值,而不是键本身。那么有没有办法删除钥匙呢?

c# dictionary key
2个回答
27
投票

Remove() 方法实际上是从字典中删除现有的键值对。您还可以使用clear方法删除字典中的所有元素。

var cities = new Dictionary<string, string>(){
    {"UK", "London, Manchester, Birmingham"},
    {"USA", "Chicago, New York, Washington"},
    {"India", "Mumbai, New Delhi, Pune"}
};

cities.Remove("UK"); // removes UK 

//cities.Remove("France"); //will NOT throw a an exception when key `France` is not found.
//cities.Remove(null); //will throw an ArgumentNullException

}

cities.Clear(); //removes all elements

您可以阅读本文以获取更多信息https://www.tutorialsteacher.com/csharp/csharp-dictionary


7
投票

文档这里有点不清楚,你是对的:

从列表中删除指定键的值 字典.

如果向下滚动一点,您会看到更好的措辞:

以下代码示例展示了如何从 使用

Remove
方法的字典。

字典中永远不存在没有值的键(即使

null
值也是一个值)。它始终是
KeyValuePair<TKey, TValue>
。所以你可以简单地使用
Remove
删除猫条目。

d.Remove("cat"); // cat gone
Console.Write(d.Count); // 1
© www.soinside.com 2019 - 2024. All rights reserved.