我想检查下面提到的字典是否包含特定的键。
Dictionary<string, Dictionary<string, Dictionary<string, string>>>
我想检查下面提到的字典是否包含特定的键。
Dictionary<string, Dictionary<string, Dictionary<string, string>>>
你必须一一检查,我猜是这样的:
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"];
}
}
}
您需要检查 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
}
}
如果您要使用外部两个字典来使其工作,您将不得不使用嵌套的 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 所以你可以明确地看到类型。