Tricky Linq Group by for time ranges

↘锁芯ラ 提交于 2019-12-08 05:45:11

问题


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.


回答1:


Try this:

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




回答2:


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 );
    }
}


来源:https://stackoverflow.com/questions/754546/tricky-linq-group-by-for-time-ranges

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!