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

标签 c# dictionary foreach nested

我有一个像这样的嵌套字典结构:

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

我尝试使用两个 foreach 循环访问元素,但编译器不允许我将以下内容用作我的内部循环的循环变量:

Dictionary<string, string>

这是我的:

foreach (string key in dict.Keys) {
    foreach (Dictionary<string, string> innerDict in dict[key]) {
        // ...
    }
}

编译器说:

Cannot convert type 'System.Collections.Generic.KeyValuePair<string,string>'
 to 'System.Collections.Generic.Dictionary<string,string>'

我可以在内循环中使用 KeyValuePair,但我想访问整个字典对象本身(这样我就可以做这样的事情:if (dict.ContainsKey(innerDict)) { ... })

最佳答案

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

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

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

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

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

但是,这是一种冗长且低效的方法来获取每个内部字典及其键。以下是应该如何完成:

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

    // Do something with key and innerDict.
}

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

请注意,我只是将 item.Keyitem.Value 中的值复制到局部变量中以说明它们的类型。当然,您可以直接使用 item.Keyitem.Value

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

foreach (var innerDict in dict.Values)
{
    // Use inner dictionary
}

关于c# - 如何在 foreach 循环中访问嵌套的 Dictionary<> 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16941267/

相关文章:

java - foreach 变量在编译时导致 "<identifier> expected"错误

c# - 如何在 CHM 文件中查找主题 ID

c# - 如何同时编写多个 Windows 窗体?

c# - 为什么字典 "does not contain a definition for ' ElementAt'”?

PHP Foreach数组转表格显示

c++ - 如何在 c++builder 中使用 IDE 管理的组件编写 for_each 循环

c# - 在 WCF 和 Windows 身份验证中处理 CORS

c# - 响应式框架 (RX) 和异步处理事件

ios - 在 iOS 中给出方向

c++ - 无法从 map 获取字符分类信息