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

标签 c# linq

我有以下内容:

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

关于c# - 合并重叠的时间间隔?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11480031/

相关文章:

xml - 如何按属性值对 LINQ C# 中的 XML 进行排序?还有MVC

c# - 使用 linq group by 从具有 DateTime 属性的对象列表获取具有间隔 StartDate、EndDate 的列表

c# - 将哈希表从 C# 传递到 PowerShell

c# - 如何处理 System.OverflowException

c# - 系统.MissingMethodException : Method not found?

c# - 托管代码能否像非托管代码一样快速地执行计算?

c# - 使用数组对 List<T> 进行排序

c# - 将 group by 查询转换为 linq

c# - Linq to Entities 中的 Expression.Coalesce

c# - 如何使用长/纬度坐标在 map 上旋转多边形?