计算多个日期/时间范围之间的交叉点的位置和数量?

时间:2010-04-29 15:18:53

标签: c# .net vb.net

我需要计算多个日期范围之间交叉点的位置以及重叠交叉点的数量。然后我需要显示哪些日期/时间范围与每个相交的部分重叠。它稍微复杂一点,所以我会尽力通过提供一个例子来解释。我在VB.Net工作,但C#示例是可以接受的,我也同时工作。

我们有几个涉及同一系统的高风险任务。下面我有三个名为HR1 / 2/3/4的示例作业,包括开始和结束日期/时间。

  • HR1 {1/6/2010 10:00 - 1/6/2010 15:00}
  • HR2 {1/6/2010 11:00 - 1/6/2010 18:00}
  • HR3 {1/6/2010 12:00 - 1/6/2010 14:00}
  • HR4 {1/6/2010 18:00 - 1/6/2010 20:00}

我想要的最终结果如下所示。我无法通过示例来描述它。

  • HRE1 {1/6/2010 10:00 - 1/6/2010 11:00} - Intersects 1
  • {结束时间拆分1,仅为了可读性,在解决方案中不需要}
  • HRE1 {1/6/2010 11:00 - 1/6/2010 12:00} - Intersects 2
  • HRE2 {1/6/2010 11:00 - 1/6/2010 12:00} - Intersects 2
  • {End Time Split 2,仅为了可读性,在解决方案中不需要}
  • HRE1 {1/6/2010 12:00 - 1/6/2010 14:00} - Intersects 3
  • HRE2 {1/6/2010 12:00 - 1/6/2010 14:00} - Intersects 3
  • HRE3 {1/6/2010 12:00 - 1/6/2010 14:00} - Intersects 3
  • {End Time Split 3,仅为了可读性,在解决方案中不需要}
  • HRE1 {1/6/2010 14:00 - 1/6/2010 15:00} - Intersects 2
  • HRE2 {1/6/2010 14:00 - 1/6/2010 15:00} - Intersects 2
  • {End Time Split 4,仅为了可读性,在解决方案中不需要}
  • HRE2 {1/6/2010 15:00 - 1/6/2010 18:00} - 相交1
  • {End Time Split 5,仅为了可读性,在解决方案中不需要}
  • HR4 {1/6/2010 18:00 - 1/6/2010 20:00} - Intersects 1

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:5)

var timePoints = (from r in ranges select r.Start)
    .Concat(from r in ranges select r.End)
    .Distinct().OrderBy(dt => dt).ToArray();

var intersections = from i in Enumerable.Range(0, timePoints.Length - 1)
                    let start = timePoints[i]
                    let end = timePoints[i + 1]
                    from range in ranges
                    where range.Start <= start && range.End >= end
                    select new { Range = range, Start = start, End = end };

编辑:修改了交叉点的代码:

var timePoints = (from r in ranges select r.Start)
    .Concat(from r in ranges select r.End)
    .Distinct().OrderBy(dt => dt).ToArray();

var intersectionGroups = from i in Enumerable.Range(0, timePoints.Length - 1)
                         let start = timePoints[i]
                         let end = timePoints[i + 1]
                         select new
                         {
                             Start = start,
                             End = end,
                             Ranges =
                                 from range in ranges
                                 where range.Start <= start && range.End >= end
                                 select range
                         };

var intersections = from intGroup in intersectionGroups
                    let count = intGroup.Ranges.Count()
                    from range in intGroup.Ranges
                    select new
                    {
                        Range = range,
                        Start = intGroup.Start,
                        End = intGroup.End,
                        Count = count
                    };

我不知道你想对结果做什么,但最好使用intersectionGroups而不是intersections