在JsonConvert之后我的Group Key发生了什么?

时间:2018-02-22 23:38:15

标签: c# json linq

我正在尝试做一个linq组,它似乎正在工作但是当我做一个JsonConvert它似乎很多。

public class StatsVm
{

        public int TotalCount { get; set; }
        public string Name { get; set; }
        public DateTime? LoggedDate { get; set; }
}

假设我有一个10个这样的对象的数组,其中5个的LoggedDate为2018-02-19,其中5个已记录2018-02-20的日期

我想按日期(不是时间部分)

对它们进行分组
var d = results.GroupBy(group => group.LoggedDate.GetValueOrDefault().ToString("yyyy-MM-dd")).ToList();

这给我一个List<IGrouping<string, StatsVm>>这就是我想要的,但是当我这样做时

JsonConvert.SerializeObject(d)

我丢失了分组键。我想它可能不是有效的json或其他东西。但是我希望在json中有这样的东西。

{
    "2018-1-1": [
        {
            "LoggedDate": "2018-1-1",
            "Name": "Test",
            "TotalCount": 20
        },
        {
            "LoggedDate": "2018-1-1",
            "Name": "Test2",
            "TotalCount": 1
        }
    ],
    "2018-1-2": [
        {
            "LoggedDate": "2018-1-2",
            "Name": "Test",
            "TotalCount": 20
        },
        {
            "LoggedDate": "2018-1-2",
            "Name": "Test2",
            "TotalCount": 1
        }
    ]
}

1 个答案:

答案 0 :(得分:1)

我能够通过使用词典来创建您需要的结果。

示例代码:

void Main()
{
    // Create dummy data
    var results = new List<StatsVm>();
    // Create dummy data
    var results = new List<StatsVm>();
    results.Add(new StatsVm { TotalCount = 20, Name = "Test", LoggedDate = new DateTime(2018, 1, 1) });
    results.Add(new StatsVm { TotalCount = 1, Name = "Test2", LoggedDate = new DateTime(2018, 1, 1) });
    results.Add(new StatsVm { TotalCount = 20, Name = "Test", LoggedDate = new DateTime(2018, 1, 2) });
    results.Add(new StatsVm { TotalCount = 1, Name = "Test2", LoggedDate = new DateTime(2018, 1, 2) });

    // Creates the dictionary
    var output = results
        .Select(r => new
        {
            LoggedDate = r.LoggedDate.GetValueOrDefault().ToString("yyyy-MM-dd"),
            Name = r.Name,
            TotalCount = r.TotalCount
        })
        .GroupBy(group => group.LoggedDate)
        .ToDictionary(t => t.Key);

    // Serializes the dictionary as a JSON string
    var serializedString = JsonConvert.SerializeObject(output, Newtonsoft.Json.Formatting.Indented);

    // Prints the serialized string
    Console.WriteLine(serializedString);
}

public class StatsVm
{

    public int TotalCount { get; set; }
    public string Name { get; set; }
    public DateTime? LoggedDate { get; set; }
}

编辑:

更新代码以将日期格式化为yyyy-mm-dd

生成的输出:

{
  "2018-01-01": [
    {
      "LoggedDate": "2018-01-01",
      "Name": "Test",
      "TotalCount": 20
    },
    {
      "LoggedDate": "2018-01-01",
      "Name": "Test2",
      "TotalCount": 1
    }
  ],
  "2018-01-02": [
    {
      "LoggedDate": "2018-01-02",
      "Name": "Test",
      "TotalCount": 20
    },
    {
      "LoggedDate": "2018-01-02",
      "Name": "Test2",
      "TotalCount": 1
    }
  ]
}