在 C# 中,可以使用嵌套循环来遍历嵌套字典。以下是一个示例代码:

Dictionary<string, Dictionary<string, int>> nestedDict = new Dictionary<string, Dictionary<string, int>>();

nestedDict['A'] = new Dictionary<string, int>();
nestedDict['A']['a1'] = 1;
nestedDict['A']['a2'] = 2;

nestedDict['B'] = new Dictionary<string, int>();
nestedDict['B']['b1'] = 3;
nestedDict['B']['b2'] = 4;

foreach (var outerKey in nestedDict.Keys)
{
    Console.WriteLine('Outer Key: ' + outerKey);
    foreach (var innerKey in nestedDict[outerKey].Keys)
    {
        Console.WriteLine('Inner Key: ' + innerKey);
        Console.WriteLine('Value: ' + nestedDict[outerKey][innerKey]);
    }
}

在这个示例中,我们定义了一个嵌套字典nestedDict,其中外层字典的键是字符串,值是内层字典。内层字典的键也是字符串,值是整数。

通过使用嵌套循环,我们可以遍历外层字典的键,然后再遍历对应内层字典的键。在循环中,我们可以访问内层字典的值。

输出将会是:

Outer Key: A
Inner Key: a1
Value: 1
Inner Key: a2
Value: 2
Outer Key: B
Inner Key: b1
Value: 3
Inner Key: b2
Value: 4

这样,我们就完成了对嵌套字典的遍历。


原文地址: https://www.cveoy.top/t/topic/quwF 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录