使用LINQ C#汇总值和时间

时间:2019-10-22 15:25:20

标签: c# list linq

我从API获得以下JSON结果。

[
    {
        "ID": "1",
        "Value" : "10",
        "TimeStamp": "2019-10-21 00:00:00"

    },
    {
        "ID": "1",
        "Value": "10",
        "TimeStamp": "2019-10-21 00:15:00"

    },
    {
        "ID": "1",
        "Value": "10",
        "TimeStamp": "2019-10-21 00:30:00"
    },
    {
        "ID": "1",
        "ResultValue": "10",
        "TimeStamp": "2019-10-21 00:45:00"
    },
    {
        "ID": "1",
        "Value": "10",
        "TimeStamp": "2019-10-21 01:00:00"

    },
    {
        "ID": "1",
        "Value": "10",
        "TimeStamp": "2019-10-21 01:15:00"

    },
    {
        "ID": "1",
        "Value": "10",
        "TimeStamp": "2019-10-21 01:30:00"
    },
    {
        "ID": "1",
        "Value": "10",
        "TimeStamp": "2019-10-21 01:45:00"
    },
    {
        "ID": "1",
        "Value": "0",
        "TimeStamp": "2019-10-21 02:00:00"
    }
]

我正在尝试反序列化并写入列表,然后汇总值

 var items = JsonConvert.DeserializeObject<List<TestData>>(JSONResult).ToList();
 var aggList = items.GroupBy(u=> new { u.ID,u.TimeStamp}).Select(g => new TestData { ID = g.Key.ID,TimeStamp = g.Key.TimeStamp ,TotalValue = g.Sum(k =>K.Value)}).ToList();

如何更改LINQ查询以显示如下所示的结果。

Id : 1
 TotalValue : 40
 TimeStamp : 2019-10-21 01:00:00

 Id : 1
 TotalValue : 40
 TimeStamp : 2019-10-21 02:00:00

1 个答案:

答案 0 :(得分:1)

您可以同时使用GroupBy日期和小时:

var aggList = items.GroupBy(u => new { u.ID, u.TimeStamp.Date, u.TimeStamp.Hour })
                            .Select(g => new TestData
                            {
                                ID = g.Key.ID,
                                TimeStamp = g.Key.Date.AddHours(g.Key.Hour),
                                Value = g.Sum(k => k.Value)
                            }).ToList();

它将给您以下结果:

ID : 1
TotalValue : 30
TimeStamp : 21.10.2019 00:00:00

ID : 1
TotalValue : 40
TimeStamp : 21.10.2019 01:00:00

ID : 1
TotalValue : 0
TimeStamp : 21.10.2019 02:00:00