简体   繁体   English

在嵌套字典中进行迭代在C#中不起作用

[英]Iterating through nested dictionary is not working in C#

I am trying to print results from nested dictionary 我正在尝试从嵌套字典中打印结果

var variations_hash = new Dictionary<string, Dictionary<string, List<string>>>();

But it throws some random error 但这会引发一些随机错误

using System;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading;

class Program
{
    static void Main()
    {
        var variations_hash = new Dictionary<string, Dictionary<string, List<string>>>();
        var variations = new Dictionary<string, List<string>>();

        variations["available"] = new List<string> { "hi" };
        var stores = new[] { "s", "m", "xl", "xxl", "xxxl", "v" };
        string color_trans = "blue";
        foreach (var sto in stores)
        {
            variations_hash[sto] = variations;
        }

        foreach(var job in variations_hash.Key())
        {
            foreach (var innerDict in variations_hash[key].Select(k => k.Value))
            {
                Console.Write(innerDict);
            }
        }
        Console.ReadLine();
    }
}

Error: 错误:

Error CS1061 'Dictionary>>' does not contain a definition for 'Key' and no extension method 'Key' accepting a first argument of type 'Dictionary>>' could be found (are you missing a using directive or an assembly reference?) 错误CS1061“字典>>”不包含“键”的定义,找不到可以接受类型为“字典>>”类型的第一个参数的扩展方法“键”(您是否缺少using指令或程序集引用?)
ConsoleApplication1 c:\\users\\administrator\\documents\\visual studio 2015\\Projects\\ConsoleApplication1\\ConsoleApplication1\\Program.cs 29 ConsoleApplication1 c:\\ users \\ administrator \\ documents \\ Visual Studio 2015 \\ Projects \\ ConsoleApplication1 \\ ConsoleApplication1 \\ Program.cs 29

Error CS0103 The name 'key' does not exist in the current context ConsoleApplication1 c:\\users\\administrator\\documents\\visual studio 2015\\Projects\\ConsoleApplication1\\ConsoleApplication1\\Program.cs 31 错误CS0103在当前上下文中不存在名称“键” ConsoleApplication1 c:\\ users \\ administrator \\ documents \\ visual studio 2015 \\ Projects \\ ConsoleApplication1 \\ ConsoleApplication1 \\ Program.cs 31

Warning CS0219 The variable 'color_trans' is assigned but its value is never used 警告CS0219已分配变量'color_trans',但从未使用过其值
ConsoleApplication1 c:\\users\\administrator\\documents\\visual studio 2015\\Projects\\ConsoleApplication1\\ConsoleApplication1\\Program.cs 20 ConsoleApplication1 c:\\ users \\ administrator \\ documents \\ Visual Studio 2015 \\ Projects \\ ConsoleApplication1 \\ ConsoleApplication1 \\ Program.cs 20

How to loop and print all the contents of nested dictionary? 如何循环和打印嵌套字典的所有内容?

Although you could correct the issue by replacing Key() with Keys proprty, this would not be the optimal way of iterating a dictionary, because you would have to retrieve the object for each key in the loop. 尽管您可以通过用Keys属性替换Key()来解决问题,但这并不是迭代字典的最佳方法,因为您必须为循环中的每个键检索对象。

It is more efficient to iterate key-value pairs, like this: 迭代键-值对更为有效,如下所示:

foreach(var vHash in variations_hash) {
    Console.WriteLine("variations_hash key = {0}", vHash.Key);
    foreach (var inner in vHash.Value) {
        // Print inner dictionary key followed by comma-separated list
        Console.WriteLine(
            "--- {0}: {1}"
        ,   inner.Key
        ,   string.Join(", ", inner.Value)
        );
    }
}

Note how each loop gives you access to not only the key of the dictionary being iterated (ie vHash.Key and inner.Key ) but also to the value associated with that key. 请注意,每个循环如何使您不仅可以访问要迭代的字典的键(即vHash.Keyinner.Key ),还可以访问与该键关联的值。

It should be variations_hash.Keys 应该是variations_hash.Keys

Also nested dictionary value is a List , so use SelectMany to flatten the structure. 另外,嵌套的字典值是List ,因此请使用SelectMany展平结构。

foreach(var job in variations_hash.Keys)
{
    foreach (var innerDict in variations_hash[key].SelectMany(k => k.Value))
    {
        Console.Write(innerDict);
    }
}

Above code might fix your compilation issues and prints all nested dictionary values, but to print the nested dictionary in proper format you could use below code. 上面的代码可能会解决您的编译问题并打印所有嵌套的字典值,但是要以正确的格式打印嵌套的字典,可以使用以下代码。

foreach(var kv in variations_hash)
{
    foreach (var nestedKv in kv.Values)
    {
        Console.Write("Key {0}- Values{1}", nestedKv.Key, string.Join(",", nestedKv.Value));
    }
}

and same thing using Linq 和使用Linq

var lines = variations_hash.SelectMany(x=>x.Values)
                           .ToList().
                           .ForEach(kv => Console.WriteLine("Key {0}- Values{1}", kv.Key, string.Join(",", kv.Value)));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM