组合两个相邻的集合以创建Json行

时间:2016-10-08 22:58:20

标签: c# .net json linq dynamic

我有一个List<Dictionary<string, List<string>>>,在使用NewtonSoft进行序列化后会给出这样的结果:

[{
    "Header1" : [
        "25%",
        "1.4%",
        "0.93%"
    ],
    "Header2" : [
        "51%",
        "42%",
        "16"
    ],
    "Header3" : [
        "8%",
        "99%",
        "11.37%"
    ]
}]

我需要将其转换为具有键值对的数据表,类似于JSON:

{
    "data":
    [{
        "Header1" : "25%",
        "Header2" : "51%",
        "Header3" : "8%",
    },
    {
        "Header1" : "1.4%",
        "Header2" : "42%",
        "Header3" : "99%",
    }]
}

如果不进行手动foreach循环,您能否建议一种优雅的方法来实现这一目标?

请注意标题的值不是静态的;我在运行时得到它们。

1 个答案:

答案 0 :(得分:0)

你可以使用Linq方法做这样的事情:

var initialData = new List<Dictionary<string, List<string>>>
{
    new Dictionary<string, List<string>>
    {
        { "Header1", new List<string> {"25%", "1.4%", "0.93%" } },
        { "Header2", new List<string> {"51%", "42%", "16%" } },
        { "Header3", new List<string> {"8%", "99%", "11.37%" } }
    },
};

var result = new
{
    data = initialData.First()
            .Select(kvp => kvp.Value.Select((v, i) => 
                           new { Key = kvp.Key, Value = v, Index = i }))
            .SelectMany(a => a)
            .GroupBy(a => a.Index)
            .Select(g => g.ToDictionary(a => a.Key, a => a.Value))
};

string json = JsonConvert.SerializeObject(result, Formatting.Indented);
Console.WriteLine(json);

上面的代码将给出这个输出:

{
  "data": [
    {
      "Header1": "25%",
      "Header2": "51%",
      "Header3": "8%"
    },
    {
      "Header1": "1.4%",
      "Header2": "42%",
      "Header3": "99%"
    },
    {
      "Header1": "0.93%",
      "Header2": "16%",
      "Header3": "11.37%"
    }
  ]
}