读取嵌套字典时出错

时间:2016-05-06 20:31:48

标签: c# dictionary nested

我想在c#中阅读嵌套字典。 声明如下:

Dictionary<string, double> dict2 = 
    new Dictionary<string, double>();
Dictionary<string, Dictionary<string, double>> dict1 = 
    new Dictionary<string,  Dictionary<string, double>>();
Dictionary<string, Dictionary<string, Dictionary<string, double>>> globalDict = 
    new Dictionary<string, Dictionary<string, Dictionary<string, double>>>();

我使用以下代码来阅读它:

foreach (var key3 in globalDict.Keys)
{
    foreach (var key2 in globalDict[key3].Keys)
    {
        foreach (var key1 in globalDict[key2].Keys)
        {
            Console.WriteLine(globalDict[key3][key2][key1]);
        }
    }
}

但是它给了我以下错误:

  

&#39; System.Collections.Generic.KeyNotFoundException&#39;

在这一行:

foreach (var key1 in globalDict [key2].Keys)

有关我使用的方法的任何建议吗?

1 个答案:

答案 0 :(得分:2)

您忘了先访问globalDict[key3],因为您已经Dictionary深了{/ p>

foreach (var key3 in globalDict.Keys)
{
     foreach (var key2 in globalDict[key3].Keys)
     {
         Console.WriteLine("Jours {0}", key2);

         foreach (var key1 in globalDict[key3][key2].Keys) // here
         {
              Console.WriteLine(globalDict[key3][key2][key1]);
         }
     }
}