【问题标题】:How can i create a nested dictionary in c#如何在 C# 中创建嵌套字典
【发布时间】:2016-05-23 07:39:01
【问题描述】:

我如何创建一个嵌套字典,下面在 c# 中给出

这是嵌套的 json

{
   "blue":[
      {
         "s":{
            [
               "store1",
               "store2"
            ],
            "availble"
         }
      },
      {
         "m":{
            [
               "store3",
               "store4"
            ],
            "not availble"
         }
      },
      {
         "l":{
            [
               "store5"
            ],
            "availble"
         }
      }
   ]
},
{
   "back":[
      {
         "xxl":{
            [
               "store2",
               "store4"
            ],
            "not availble"
         }
      },
      {
         "m":{
            [
               "store3",
               "store4"
            ],
            "not availble"
         }
      }

   ]
}

我尝试了下面的脚本,但它不起作用

var variations_hash = new Dictionary<string, List<string>>();
var stores = new[] {"s","m","xl","xxl","xxxl","v"};
var color_trans = new[] {"blue","black"};
foreach(var store in stores){
if (variations_hash.ContainsKey (color_trans)) {

        List<String> list;
        if (variations_hash.TryGetValue (color_trans, out list)) {
        list.Add (store);
        }

    } else {

       variations_hash[color_trans] = new List<string> { store };
      }
}

如何在 c# 中创建嵌套字典?

我想要上述格式的嵌套字典

【问题讨论】:

  • 你试过Dictionary&lt;string, Dictionary&lt;string, string&gt;&gt;吗?
  • 不,如果您有解决方案,请添加代码作为答案吗?
  • 您发布的 JSON 无效。检查它在JSONLint.com
  • 你确定json有效吗?

标签: c# json dictionary nested


【解决方案1】:

这是一种生成嵌套字典的简单、优雅的方法

Dictionary<int, Dictionary<int, string>> dict = things
    .GroupBy(thing => thing.Foo)
    .ToDictionary(fooGroup => fooGroup.Key,
                  fooGroup => fooGroup.ToDictionary(thing => thing.Bar,
                                                    thing => thing.Baz));

如果有帮助,请告诉我,在我看来,这是生成嵌套字典的最有效方式。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-28
    • 1970-01-01
    • 1970-01-01
    • 2013-04-26
    • 1970-01-01
    • 2016-10-06
    • 1970-01-01
    • 2023-01-18
    相关资源
    最近更新 更多