0

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

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

3 回答 3

3

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

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"];
        }

    }
}
于 2013-11-14T15:24:50.007 回答
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
    }
 }
于 2013-11-14T15:22:39.667 回答
1

如果您要使用外部两个字典来使其工作,您将不得不使用嵌套的 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 所以你可以明确地看到类型。

于 2013-11-14T15:32:04.603 回答