C# – Tricky Linq Group by for time ranges

c++datetimelinqlinq-group

I have a class that represents a shift that employee's can work:

public class Shift {
    public int Id { get; set;}
    public DateTime Start {get;set;}
    public DateTime End { get; set;}
    public DayOfWeek Day { get; set;}
}

And say I have a list of these shifts for a single employee:

List<Shift> myShifts;

I know I can get group the shifts by day with the following linq statement:

var shiftsByDay = from a in myShift
                  group a by a.Day;

My question: For each day, how can I get all the shifts that overlap, in separate groups, without double counting?

An overlapping shift is one where either the start or end times overlap with another shifts start or end times.

I'd love to be able to do this with linq if at all possible.

Best Solution

First, I think it would be easier if you gave each shift some unique identifier so that you can distinguish it. Then I think you can use Where to choose each element that has any conflicts with another element in the collection. Finally you can group them by day. Note this won't tell you which shifts conflict, just the ones that have a conflict on any given day.

public class Shift {
    public int ID { get; set; }
    public DateTime Start {get;set;}
    public DateTime End { get; set;}
    public DayOfWeek Day { get; set;}
}

var query = shifts.Where( s1 => shifts.Any( s2 => s1.ID != s2.ID
                                        && s1.Day == s2.Day
                                        && (s2.Start <= s1.Start && s1.Start <= s2.End)
                                             || (s1.Start <= s2.Start && s2.Start <= s1.End))
                  .GroupBy( s => s.Day );

foreach (var group in query.OrderBy( g => g.Key ))
{
    Console.WriteLine( group.Key ); // Day of Week
    foreach (var shift in group)
    {
         Console.WriteLine( "\t" + shift.ID );
    }
}