【问题标题】:How to check containsKey in Dictionary<string, Dictionary<string, Dictionary<string, string>>> [closed]如何检查 Dictionary<string, Dictionary<string, Dictionary<string, string>>> 中的 containsKey [关闭]
【发布时间】:2013-11-14 15:20:25
【问题描述】:

我想检查下面提到的字典是否包含特定的键。

Dictionary<string, Dictionary<string, Dictionary<string, string>>>

【问题讨论】:

  • 哇。哪个字典的键?
  • 我想检查所有三个标签......
  • 您遇到了什么问题? .ContainsKey 并不是一个很难调用的方法......即使你想查看内部字典,那也只是一个 foreach 在孩子们身上。看起来你自己没有尝试过任何东西。
  • 考虑重新设计您的数据结构
  • 你不能有效地检查最里面的字典。

标签: c# .net generics collections


【解决方案1】:

你得一一检查,我猜是这样的:

Dictionary<string, Dictionary<string, Dictionary<string, string>>> dictionary =
    new Dictionary<string, Dictionary<string, Dictionary<string, string>>>();
if (dictionary.ContainsKey("someKey"))
{
    var secondDictionary = dictionary["someKey"];
    if (secondDictionary.ContainsKey("otherKey"))
    {
        var thirdDictionary = secondDictionary["otherKey"];
        if (thirdDictionary.ContainsKey("thirdKey"))
        {
            var final = thirdDictionary["thirdKey"];
        }

    }
}

【讨论】:

  • 谢谢...帮助....
  • @user1667760,我不确定这样的数据结构是否对您有帮助,我希望您只是尝试测试一些代码,否则这种数据结构可能会导致您变得复杂和可能表现不佳
  • 而不是使用 ContainsKey 然后在索引器查找中执行,您应该执行 TryGetValue;否则,索引器最终会在内部再次调用 ContainsKey。如果您多次调用字典,尤其是递归调用,它可以极大地提升性能。
【解决方案2】:

您需要检查 3 个键,一个用于外部字典,一个用于内部字典。

Dictionary<string, Dictionary<string, Dictionary<string, string>>> dict= new Dictionary<string, Dictionary<string, Dictionary<string, string>>>(); 
 if (dict.ContainsKey(outerKey))
 {
   var innerDict = dict[outerKey];
   if (innerDict.ContainsKey(innerKey))
   {  
       var innerMost = innerDict[innerKey];
       if (innerMost.ContainsKey(innerMostKey))
        var item = innerMost[innerMostKey]; // This is the item of inner most dict
    }
 }

【讨论】:

  • 谢谢...帮助....
【解决方案3】:

如果要让外部两个字典起作用,则必须使用嵌套的 foreach 循环。

有点像

        var nestedDictionary = new Dictionary<string, Dictionary<string, Dictionary<string, string>>>();
        var foundCounter = 0;
        foreach (KeyValuePair<string, Dictionary<string, Dictionary<string, string>>> midLevel in nestedDictionary)
        {
            var key = midLevel.Key;
            if (key.Equals("WHATAMILOOKINGFOR"))
            {
                foundCounter++;
            }
            foreach (KeyValuePair<string, Dictionary<string, string>> lowerLevel in midLevel.Value)
            {
                if (key.Equals("WHATAMILOOKINGFOR"))
                {
                    foundCounter++;
                }
                if(lowerLevel.Value.ContainsKey("WHATAMILOOKINGFOR"))
                {
                    foundCounter++;
                }
            }
        }

我没有在 foreach 上使用 var,所以你可以明确地看到类型。

【讨论】:

    猜你喜欢
    • 2014-10-22
    • 1970-01-01
    • 2012-09-21
    • 2012-03-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多