首页 > 解决方案 > 使用 LINQ 按每 n 天对数据进行分组

问题描述

我有以下课程:

public class TotalPaymentStatistics 
{ 
     public DateTime RegisteredAt { get; set; }
     public double TotalAmount { get; set; }  
}

此外,我在数据库中存储了以下示例数据:

2021-01-01 | 120
2021-01-02 | 120
2021-01-03 | 120
2021-01-04 | 120
2021-01-05 | 120
2021-01-06 | 120
2021-01-07 | 120
2021-01-08 | 120
2021-01-09 | 120
2021-01-10 | 120

如何以这样的方式对此类的对象进行分组,当我传递参数时,例如 5,(5 - 是一个时间范围,这意味着我想在整个集合中每 5 天接收一次汇总数据),我将收到以下结果:

2021-01-01 600
2021-01-05 600

提前致谢

标签: c#linq

解决方案


<pre>
void Main()
{
    var items = new List<TotalPaymentStatistics>()
    {
        new TotalPaymentStatistics(){RegisteredAt = new DateTime(2021,1,1),TotalAmount = 120},
        new TotalPaymentStatistics(){RegisteredAt = new DateTime(2021,1,2),TotalAmount = 120},
        new TotalPaymentStatistics(){RegisteredAt = new DateTime(2021,1,3),TotalAmount = 120},
        new TotalPaymentStatistics(){RegisteredAt = new DateTime(2021,1,4),TotalAmount = 120},
        new TotalPaymentStatistics(){RegisteredAt = new DateTime(2021,1,5),TotalAmount = 120},
        new TotalPaymentStatistics(){RegisteredAt = new DateTime(2021,1,6),TotalAmount = 120},
        new TotalPaymentStatistics(){RegisteredAt = new DateTime(2021,1,7),TotalAmount = 120},
        new TotalPaymentStatistics(){RegisteredAt = new DateTime(2021,1,8),TotalAmount = 120},
        new TotalPaymentStatistics(){RegisteredAt = new DateTime(2021,1,9),TotalAmount = 120},
        new TotalPaymentStatistics(){RegisteredAt = new DateTime(2021,1,10),TotalAmount = 120},
    };
    DateTime day0 = items[0].RegisteredAt.AddDays(-1);
    var q = items
        .GroupBy(x => ((int)((x.RegisteredAt.Subtract(day0).TotalDays-1) / 5)))
        .Select(x => new {
            x.Key,
            Date = day0.AddDays(x.Key*5+1),
            Amount = x.Sum(y => y.TotalAmount)
        });
    foreach(var item in q)
    {
        Console.WriteLine($"{item.Date.ToString("yyyy-MM-dd")} {item.Amount}");
    }
}

// Define other methods and classes here
public class TotalPaymentStatistics
{
    public DateTime RegisteredAt { get; set; }
    public double TotalAmount { get; set; }
}
</pre>

这会给你:

2021-01-01 600

2021-01-06 600


推荐阅读