Reputation: 129
Hi I'm attempting to group a collection of objects by their DateTime property and I am having a strange issue. Currently I have the following:
TimeSpan interval = TimeSpan.FromMinutes(45);
var selected = from date in item.Dates
group date by (date.Ticks / interval.Ticks) into g
select g;
this basically works, but if the time of the first item is 11:45 then the first group is only 15 mins long. Followed by the next group starting at 12:00 and from there grouping correctly. Am I missing something really simple, or do I need to change the way I attempt to group? What I'm really trying to do is group all my objects into 45 minute chunks.
Upvotes: 3
Views: 1367
Reputation: 437336
The issue here is that you have defined the unit in the "time group axis" (45 minutes), but you have not explicitly defined where the axis starts.
With the current code grouping will start at 00:00, so by adding 45 minutes each time you eventually get to 11:15, which is the start of the 11:15-12:00 group. The time of the first event that actually goes into that group plays no role.
If you want 45-minute groups starting from the exact time the first event occurs compensate:
// In your current version this is effectively TimeSpan.Zero
var startOfAxis = item.Dates.Min().TimeOfDay;
var interval = TimeSpan.FromMinutes(45);
var selected =
from date in item.Dates
group date by ((date.Ticks - startOfAxis.Ticks) / interval.Ticks) into g
select g;
Upvotes: 1
Reputation: 18877
You just need to offset all of the dates before grouping.
TimeSpan offset = startTime.TimeOfDay;
TimeSpan interval = TimeSpan.FromMinutes(45);
var selected = from date in item.Dates
group date by ((date.Ticks - offset.Ticks) / interval.Ticks) into g
select g;
Upvotes: 2