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

How to remove a KEY from a dictionary in c#

我有一本名为 d 的字典。

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

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

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

Removes the value with the specified key from the Dictionary<TKey,TValue>.

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

The following code example shows how to remove a key/value pair from a dictionary using the Remove method.

字典中从来没有没有值的键(即使 null 值也是一个值)。它始终是 KeyValuePair<TKey, TValue>。所以你可以简单地使用 Remove 删除猫条目。

d.Remove("cat"); // cat gone
Console.Write(d.Count); // 1

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"); //throws run-time exception: KeyNotFoundException

if(cities.ContainsKey("France")){ // check key before removing it
    cities.Remove("France");
}

cities.Clear(); //removes all elements

您可以阅读此内容了解更多信息https://www.tutorialsteacher.com/csharp/csharp-dictionary