C# 从嵌套字典中删除项目

C# Remove item from nested dictionary

我有一个简单的问题,但我的脑子一片空白:我有一个看起来像这样的字典:

Dictionary<string, Dictionary<string, string>> dict;

据我所知,dict.Remove() 会按键删除任何条目,但我只需要从最里面的字典中删除一个项目。我该怎么做?

大概您有两个键:一个用于外部字典,一个用于嵌套字典。

因此假设您知道该条目存在,您可以使用

dict[outerKey].Remove(innerKey);

如果你不知道该条目是否存在,你想要这样的东西:

Dictionary<string, string> innerDict;
if (dict.TryGetValue(outerKey, out innerDict))
{
    // It doesn't matter whether or not innerKey exists beforehand
    innerDict.Remove(innerKey);
}

尝试

dict["key"].Remove("childkey");

注意键是字符串值。

如果你只有内键,你可以这样做:

string removeKey = "42";

Dictionary<String, String> removeDict = dict.Select(d=> d.Value).FirstOrDefault(d => d.ContainsKey(removeKey));

if(removeDict !=null)  
    removeDict.Remove(removeKey);

在此实现中,如果有多个寄存器具有相同的 innerKey,则只删除第一个匹配项