Andrey Pilip
Andrey Pilip

Reputation: 23

Dictionary of dictionaries to list

I need to create a list of names that are keys to dictionary. As for me it looks totally OK, but i have couple of errors. Structure must be like

{ paperony => {Tomatoes, 1}, {Carrot,4}, vegetarian => {Tomatoes, 4}, {Potatoes, 6} }

List<Dictionary<string, Dictionary<string, int>>> ingredients = new List<Dictionary<string, Dictionary<string, int>>>();
ingredients.Add(new Dictionary<string, Dictionary<string, int>>()
            {
                {
                    "Paperoni", 
                    {
                        {"Tomatoes", 1},
                        {"Carrot", 4}
                    }
                },

                {
                    "Vegetarian",
                    {
                        {"Tomatoes", 4},
                        {"Potatoes", 6}
                    }
                }
            }

        );

Upvotes: 0

Views: 195

Answers (1)

Anu Viswan
Anu Viswan

Reputation: 18155

You need to use explicit initialization of Dictionary. For example,

ingredients.Add(new Dictionary<string, Dictionary<string, int>>()
            {
                {
                    "Paperoni", 
                    new Dictionary<string, int>{
                        {"Tomatoes", 1},
                        {"Carrot", 4}
                    }
                },

                {
                    "Vegetarian",
                    new Dictionary<string, int>{
                        {"Tomatoes", 4},
                        {"Potatoes", 6}
                    }
                }
            }

        );

If you want to avoid usage of explicit initialization , you could use the following approach.

ingredients.Add(new Dictionary<string, Dictionary<string, int>>()
            {
                ["Paperoni"] = {
                                ["Tomatoes"]= 1,
                                ["Carrot"]= 4
                                },
                ["Vegetarian"] = 
                                {
                               ["Tomatoes"]= 4,
                               ["Potatoes"]= 6
                                }
            }

        );

Upvotes: 2

Related Questions