I\'m trying to understand how LINQ can be used to group data by intervals of time; and then ideally aggregate each group.
Finding numerous examples with explicit dat
I'd suggest using new DateTime() to avoid any issues with sub millisecond differences
var versionsGroupedByRoundedTimeAndAuthor = db.Versions.GroupBy(g =>
new
{
UserID = g.Author.ID,
Time = RoundUp(g.Timestamp, TimeSpan.FromMinutes(2))
});
With
private DateTime RoundUp(DateTime dt, TimeSpan d)
{
return new DateTime(((dt.Ticks + d.Ticks - 1) / d.Ticks) * d.Ticks);
}
N.B. I am here grouping by Author.ID as well as the rounded TimeStamp.
RoundUp function taken from @dtb answer here https://stackoverflow.com/a/7029464/661584
Read about how equality down to the millisecond doesn't always mean equality here Why does this unit test fail when testing DateTime equality?