c# - 要列出的词典词典
问题描述
我需要创建一个名称列表,这些名称是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}
}
}
}
);
解决方案
您需要使用字典的显式初始化。例如,
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
}
}
);
推荐阅读
- c# - 我可以为 MemoryStream 设置固定长度吗?
- regex - VSCode Code-Snippets 转换:同时小写和大写
- swift - Swift 中的“相邻运算符位于非关联优先级组‘ComparisonPrecedence’中”错误
- java - 正则表达式接受字符周围的任何特殊字符
- firebase - 将 Firebase Google Analytic 数据导入 BigQuery 时,Google 是否会收取流媒体费用?
- pandas - 熊猫:数据框 cumsum ,如果其他列为假则重置
- unity3d - 在 Unity 中接收动态链接
- python-3.x - Jupyter Notebook 启动时出现迁移错误
- ruby-on-rails - MailChimp 从 Ruby on Rails 取消订阅/重新订阅
- python - 多处理——线程池内存泄漏?