如何在foreach循环中访问嵌套的Dictionary <>对象

use*_*816 5 c# foreach dictionary nested

我有一个嵌套的Dictionary结构,如下所示:

Dictionary<string, Dictionary<string, string>> dict;
Run Code Online (Sandbox Code Playgroud)

我正在尝试使用两个foreach循环访问元素,但编译器不会让我使用以下作为内部循环的循环变量:

Dictionary<string, string>
Run Code Online (Sandbox Code Playgroud)

这就是我所拥有的:

foreach (string key in dict.Keys) {
    foreach (Dictionary<string, string> innerDict in dict[key]) {
        // ...
    }
}
Run Code Online (Sandbox Code Playgroud)

编译器说:

Cannot convert type 'System.Collections.Generic.KeyValuePair<string,string>'
 to 'System.Collections.Generic.Dictionary<string,string>'
Run Code Online (Sandbox Code Playgroud)

我可以在内部循环中使用KeyValuePair <string,string>,但我想从整体上访问字典对象(这样我就可以这样做:if(dict.ContainsKey(innerDict)){... })

Mat*_*son 5

修复它的最小代码更改是这样的(但请参阅此答案中下一个代码段中的正确方法):

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

foreach (string key in dict.Keys)
{
    foreach (var innerDict in dict[key].Select(k => k.Value))
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

您的问题是,当您枚举字典时,您会得到一系列键/值对.在你的情况下,价值是内在的字典,它你需要的.

我正在使用Linq"Select()"操作将每个键/值对转换为值部分,即字典,它是键/值对中的值.

然而,这是一个冗长而低效的方式来获取每个内部字典及其键.这是应该怎么做的:

foreach (var item in dict)
{
    string key = item.Key;
    Dictionary<string, string> innerDict = item.Value;

    // Do something with key and innerDict.
}
Run Code Online (Sandbox Code Playgroud)

我假设您正在尝试依次访问每个内部字典,同时在外部字典中知道内部字典的密钥.

请注意,我只从复制的值item.Key,并item.Value到本地变量来说明其类型.你可以只使用item.Keyitem.Value直接的,当然.

如果你真的只想要内部词典本身(并且你不需要每个内部词典的键),你可以这样做(如Nuffin建议的那样):

foreach (var innerDict in dict.Values)
{
    // Use inner dictionary
}
Run Code Online (Sandbox Code Playgroud)


Mik*_*oud 1

那是因为键的值string不是列表。如果您想要的话,请将 的声明更改Dictionary为。Dictionary<string, List<Dictionary<string, string>>> dict;

或者你可以在第一个循环中获取字典,foreach如下所示:

Dictionary<string, string> val = dict[key];
Run Code Online (Sandbox Code Playgroud)

并从那里使用它。但无论哪种方式,你都试图迭代一些不可枚举的东西。

我认为你可能有Dictionary你想要的定义 - 你只是不需要内部循环。