Mounarajan
Mounarajan

Reputation: 1437

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?)
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

Warning CS0219 The variable 'color_trans' is assigned but its value is never used
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?

Upvotes: 0

Views: 1629

Answers (2)

Hari Prasad
Hari Prasad

Reputation: 16986

It should be variations_hash.Keys

Also nested dictionary value is a List, so use SelectMany to flatten the structure.

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

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

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727077

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.

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 (i.e. vHash.Key and inner.Key) but also to the value associated with that key.

Upvotes: 2

Related Questions