Merging overlapping time intervals?

Viewed 7411

I have the following:

public class Interval
{
   DateTime Start;
   DateTime End; 
}

I have a List<Interval> object containing multiple intervals. I am trying to achieve the following (I used numbers to make it easy to understand):

[(1, 5), (2, 4), (3, 6)] --->  [(1,6)]
[(1, 3), (2, 4), (5, 8)] --->  [(1, 4), (5,8)]

I currently do this in Python as follows:

def merge(times):
    saved = list(times[0])
    for st, en in sorted([sorted(t) for t in times]):
        if st <= saved[1]:
            saved[1] = max(saved[1], en)
        else:
            yield tuple(saved)
            saved[0] = st
            saved[1] = en
    yield tuple(saved)

but am trying to achieve the same in C# (LINQ would be best but optional). Any suggestions on how to do this efficiently?

5 Answers
Related