views:

531

answers:

2

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.

+2  A: 

Try this:

http://staceyw.spaces.live.com/Blog/cns!F4A38E96E598161E!993.entry

geoff
Thanks lemme give that a try!
Alan
+1  A: 

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 );
    }
}
tvanfosson
Thank tvanfosson, I omitted the fact that each shift has a uniqueID, but they do have them. Lemme edit it.
Alan