如果数据列出了数月的数据,我需要计算过去2周的总和。我可以通过在14天甚至7天内打破清单并计算每个清单的总和来做到这一点。
是否有一种优雅的方式来实现上述目标?
数据列表示例如下所示:
startDate 2012-05-01
value 1
startDate 2012-05-02
value 1
........
startDate 2012-05-31
value 1
感谢。
答案 0 :(得分:2)
你的意思是你想要过去两周每个的总和,或过去两周内的单个值吗?后者比前者容易:
DateTime end = DateTime.Today;
// Note: inclusive at both ends, so this gives us 14 days in total
DateTime start = end.AddDays(-13);
var sum = data.Where(x => x.StartDate >= start && x.StartDate <= end)
.Sum(x => x.Value);
请注意,在此处评估DateTime.Today
一次非常重要,否则如果查询在午夜“周围”执行,则最终可能会出现一组不一致的比较。
如果您的数据未包含任何未来值,则可以删除end
部分。您还应该仔细考虑是否真的要减去13天或14天。
编辑:好的,现在你已经澄清了要求,听起来像最简单的方法实际上是执行两个查询 - 一个用于过去7天,一个用于7天之前那。或者,您可以通过分组来使用它:
DateTime end = DateTime.Today;
// Note: inclusive at both ends, so this gives us 14 days in total
DateTime start = end.AddDays(-13);
var sum = data.OrderBy(x => x.StartDate)
.Where(x => x.StartDate >= start && x.StartDate <= end)
.GroupBy(x => ((int) (end - x.StartDate).TotalDays) / 7)
.Select(g => new { Start = g.First().StartDate,
Sum = g.Sum(x => x.Value) });