【发布时间】:2017-02-28 11:42:42
【问题描述】:
我需要检查 DateTime-span 是否与任何现有的时间块重叠。
我的函数应该检查是否有任何重叠 并且将运行数百次,新的开始和结束日期之间的时间跨度为 10 分钟。 现有时间块的跨度可能是 5-60 分钟长。
收到的第一个 span 始终是最早的日期,收到的最后一个 span 始终是最晚的日期。 existingTimeBlocks 列表也按 StartDate 排序
private bool TimeBlockIsOverLapping(DateTime newTimeBlockStart, DateTime newTimeBlockEnd, IEnumerable<TimeBlock> existingTimeBlocks)
{
// The new TimeBlock starts later than latest existing TimeBlock or ends earlier that first existing timeblock so it won't overlap
if (existingTimeBlocks.Count() == 0)
{
return false;
}
// The new TimeBlock is within the scope of old TimeBlocks and might overlap
else
{
// TODO: Insert overlap checks here
}
}
编辑:TimeBlock 的简化定义:
public class TimeBlock
{
[Required]
public int Id { get; set; }
[Required]
public DateTime StartTime { get; set; }
[Required]
public DateTime EndTime { get; set; }
[Required]
public int ScheduleId { get; set; }
[Required]
public virtual Schedule Schedule { get; set; }
}
编辑:进一步澄清: existingTimeBlocks 可以是例如每周一和周四的 9:00 - 12:00 和 13:00-16:00 共 6 周,因此可以在周一的 12:00 和 13:00 之间传递 60 分钟的 timeSpan 和有效
【问题讨论】:
-
existingTimeBlocks.Count() 你不应该……接受
IEnumerable的方法的第一条规则是只枚举一次。 -
它看起来像一个家庭任务。你尝试过什么吗?没有人会为你做你的工作。
-
请问可以添加
TimeBlock的定义吗? -
@RobLang 根据最后一段问题,它可能包括 StartDate 和 EndDate ;)
-
要指定的一件重要事情是您的时间范围是关闭的还是半开放的。对于这些事情,通常使用半开间隔,其中开始时间包含在范围内,但结束时间不包含在范围内。这使您可以(例如)更轻松地表示整个小时,而不会意外地在两个不同范围内包含一个精确小时的时间。
标签: c#