集团的DateTime用任意时间间隔 [英] Group DateTime by an arbitrary time interval
问题描述
我有一个这样定义的项目类的IEnumerable
I have an IEnumerable of an item class defined like this:
public class Item {
public DateTime Date { get; private set; }
public decimal? Value { get; private set; }
public Item(DateTime date, decimal? value) {
Date = date;
Value = value;
}
}
这些项目是在一个特定的时间间隔(5分钟举个例子)。我需要给他们组的日期,但改变的时间间隔。例如,如果该项目是按以下顺序:
These items are in a specific time interval (5 minutes for exemple). I need to group them by the date, but changing the interval. For example, if the items are in the following order:
2010-08-24 00:05
2010-08-24 00:10
2010-08-24 00:15
2010-08-24 00:20
2010-08-24 00:25
2010-08-24 00:30
和我想它们分成15分钟车间隔,结果应该看起来像这样的:
and I want to group them into a 15 minutes interval, the result should look like this:
2010-08-24 00:15
2010-08-24 00:30
间隔由另一个类提供的,但我可以得到代表间隔(例如毫秒,Interval.FromMinutes (5).GetMilliseconds()应该返回300000)。现在的问题是我怎么能写一个分组功能,可以让我做这样的事情:数据= items.GroupBy(T => GroupingFunction(t.DateTime,间隔))
并获得结果。
The interval is provided by another class, but I can get the milliseconds that represent that interval (for example, Interval.FromMinutes(5).GetMilliseconds() should return 300000). The question is how can I write a grouping function that allows me to do something like this : data = items.GroupBy(t => GroupingFunction(t.DateTime, interval))
and obtain that result?
更新:的时间间隔不会必然在几分钟内。它可能是小时,分钟或甚至几天。
Update: the interval will not be necessarily in minutes. It could be in hours, minutes or even days.
推荐答案
像这样的事情?
DateTime[] dateTimes = new[]
{
new DateTime(2010, 8, 24, 0, 5, 0),
new DateTime(2010, 8, 24, 0, 10, 0),
new DateTime(2010, 8, 24, 0, 15, 0),
new DateTime(2010, 8, 24, 0, 20, 0),
new DateTime(2010, 8, 24, 0, 25, 0),
new DateTime(2010, 8, 24, 0, 30, 0)
};
TimeSpan interval = new TimeSpan(0, 15, 0); // 15 minutes.
var groupedTimes = from dt in dateTimes
group dt by dt.Ticks/interval.Ticks
into g
select new {Begin = new DateTime(g.Key*interval.Ticks), Values = g.ToList()};
foreach (var value in groupedTimes)
{
Console.WriteLine(value.Begin);
Console.WriteLine("\t{0}", String.Join(", ", value.Values));
}
这篇关于集团的DateTime用任意时间间隔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!