LINQ骨料和组按时间段 [英] LINQ aggregate and group by periods of time
问题描述
我想了解LINQ如何使用通过的时间间隔组数据;然后最好汇总各组。
I'm trying to understand how LINQ can be used to group data by intervals of time; and then ideally aggregate each group.
寻找具有明确的日期范围的例子不胜枚举,我被时期,如5分钟,1小时,1设法组。日
Finding numerous examples with explicit date ranges, I'm trying to group by periods such as 5-minutes, 1-hour, 1-day.
例如,我有一个包装一个DateTime与值的类:
For example, I have a class that wraps a DateTime with a value:
public class Sample
{
public DateTime timestamp;
public double value;
}
这些意见都包含在一个列表集合了一系列的:
These observations are contained as a series in a List collection:
List<Sample> series;
所以,通过时间和平均聚合值每小时时段组,我试图做是这样的:在
So, to group by hourly periods of time and aggregate value by average, I'm trying to do something like:
var grouped = from s in series
group s by new TimeSpan(1, 0, 0) into g
select new { timestamp = g.Key, value = g.Average(s => s.value };
这是根本性的缺陷,因为这组的时间跨度本身。我不知道如何使用的时间跨度(或代表一个区间的任何数据类型)查询。
This is fundamentally flawed, as it groups the TimeSpan itself. I can't understand how to use the TimeSpan (or any data type representing an interval) in the query.
推荐答案
您可以圆时间戳到下一个边界(即下降到过去最接近5分钟边界),并使用它作为您的分组:
You could round the time stamp to the next boundary (i.e. down to the closest 5 minute boundary in the past) and use that as your grouping:
var groups = series.GroupBy(x =>
{
var stamp = x.timestamp;
stamp = stamp.AddMinutes(-(stamp.Minute % 5));
stamp = stamp.AddMilliseconds(-stamp.Millisecond - 1000 * stamp.Second);
return stamp;
})
.Select(g => new { TimeStamp = g.Key, Value = g.Average(s => s.value) })
.ToList();
上面实现,通过在分组,这台分钟到前5中使用一个修改的时间戳分钟边界并删除秒和毫秒。当然的同样的方法可以用于其他时间段,即时间和天
Above achieves that by using a modified time stamp in the grouping, which sets the minutes to the previous 5 minute boundary and removes the seconds and milliseconds. The same approach of course can be used for other time periods, i.e. hours and days.
修改强>
在此基础上提出了样本输入:
Based on this made up sample input:
var series = new List<Sample>();
series.Add(new Sample() { timestamp = DateTime.Now.AddMinutes(3) });
series.Add(new Sample() { timestamp = DateTime.Now.AddMinutes(4) });
series.Add(new Sample() { timestamp = DateTime.Now.AddMinutes(5) });
series.Add(new Sample() { timestamp = DateTime.Now.AddMinutes(6) });
series.Add(new Sample() { timestamp = DateTime.Now.AddMinutes(7) });
series.Add(new Sample() { timestamp = DateTime.Now.AddMinutes(15) });
制作了3组对我来说,其中一个分组时间戳3:05,一个有3:10和一个用下午3:20(您的结果可能会有所不同基于当前时间)。
3 groups were produced for me, one with grouping timestamp 3:05, one with 3:10 and one with 3:20 pm (your results may vary based on current time).
这篇关于LINQ骨料和组按时间段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!