c# - 使用 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
提前致谢
解决方案
<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
推荐阅读
- php - 使用带有计数的选择子查询的错误mysql查询
- php - 如何将对象放入字符串并打印
- python - 正则表达式命名方案python
- delphi - 如何使 TidFTPServer 与 SSL 一起工作
- memory - 减少嵌入式目标的 Valgrind 内存使用
- regex - perl 多行问题:需要一个衬里来打印文件中字符串之前的最后一个匹配项
- java - Spring ReactiveCrudRepository ExistsQuery 方法返回 null
- html - 选择带有新行问题的选项
- sql - Hive SQL Cast 返回整数
- rust - From trait 实现可以是有损的吗?