【问题标题】:C# Remove item from nested dictionaryC#从嵌套字典中删除项目
【发布时间】:2015-04-25 19:46:02
【问题描述】:

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

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

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

【问题讨论】:

  • 获取内部字典并调用Remove()。即,获取父字典中键指定的值。
  • 嵌套字典有异味。使用适当的数据结构。它可能是某个类的字典,而该类又具有字典。不是嵌套字典。

标签: c# dictionary nested


【解决方案1】:

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

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

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);
}

【讨论】:

    【解决方案2】:

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

    string removeKey = "42";
    
    Dictionary<String, String> removeDict = dict.Select(d=> d.Value).FirstOrDefault(d => d.ContainsKey(removeKey));
    
    if(removeDict !=null)  
        removeDict.Remove(removeKey);
    

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

    【讨论】:

      【解决方案3】:

      试试

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

      注意键是字符串值。

      【讨论】:

        猜你喜欢
        • 2015-01-26
        • 1970-01-01
        • 2017-03-08
        • 2018-04-14
        • 2018-06-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多