c# – 合并重叠的时间间隔?

我有以下内容:

public class Interval
{
   DateTime Start;
   DateTime End; 
}

我有一个List< Interval>包含多个间隔的对象.我试图实现以下(我使用数字使其易于理解):

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

我目前在Python中这样做如下:

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)

但我试图在C#中实现相同(LINQ将是最好但可选).有关如何有效地做到这一点的任何建议?

这是一个使用yield return的版本 – 我发现它比执行Aggregate查询更容易阅读,尽管它仍然是懒惰的评估.这假设您已经订购了列表,如果没有,只需添加该步骤.

IEnumerable<Interval> MergeOverlappingIntervals(IEnumerable<Interval> intervals)
{
  var accumulator = intervals.First();  
  intervals = intervals.Skip(1);

  foreach(var interval in intervals)
  {
    if ( interval.Start <= accumulator.End )
    {
        accumulator = Combine(accumulator, interval);
    }
    else
    {
        yield return accumulator;
        accumulator = interval;     
    }       
  }

  yield return accumulator;
}

Interval  Combine(Interval start, Interval end)
{
  return new Interval 
  {
    Start = start.Start,
    End = Max(start.End, end.End),
  };
}

private static DateTime Max(DateTime left, DateTime right) 
{
    return (left > right) ? left : right;
}
翻译自:https://stackoverflow.com/questions/11480031/merging-overlapping-time-intervals

转载注明原文:c# – 合并重叠的时间间隔?