首页 > 解决方案 > 要列出的词典词典

问题描述

我需要创建一个名称列表,这些名称是dictionary的键。至于我,它看起来完全没问题,但我有几个错误。结构必须像

{ paperony => {西红柿,1},{胡萝卜,4},素食者 => {西红柿,4},{土豆,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}
                    }
                }
            }

        );

标签: c#

解决方案


您需要使用字典的显式初始化。例如,

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}
                    }
                }
            }

        );

如果要避免使用显式初始化,可以使用以下方法。

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

        );

推荐阅读