我需要检查DateTime-span是否与任何现有时间块重叠。
我的功能应该检查是否有任何重叠 并且将以新的开始和结束日期运行几百次,中间跨度为10分钟。 现有TimeBlocks的跨度可能是5-60分钟。
收到的第一个跨度将始终是最早的日期,收到的最后一个跨度将始终是最新日期。 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周,所以60分钟的timeSpan可以在12:00到13:00之间的星期一传递。是vaild
答案 0 :(得分:1)
类似的东西:
private static bool TimeBlockIsOverLapping(DateTime newTimeBlockStart, DateTime newTimeBlockEnd, IEnumerable<TimeBlock> existingTimeBlocks) {
foreach (var block in existingTimeBlocks) {
// This is only if existingTimeBlocks are ordered. It is only
// a speedup
if (newTimeBlockStart > block.EndTime) {
break;
}
// This is the real check. The ordering of the existingTimeBlocks
// is irrelevant
if (newTimeBlockStart <= block.EndTime && newTimeBlockEnd >= block.StartTime) {
return true;
}
}
return false;
}
要检查重叠块,我使用了Algorithm to detect overlapping periods
答案 1 :(得分:1)
好吧,让我们实施:
// static: we don't want "this" in the context
private static bool TimeBlockIsOverLapping(DateTime newTimeBlockStart,
DateTime newTimeBlockEnd,
IEnumerable<TimeBlock> existingTimeBlocks) {
if (null == existingTimeBlocks)
return false;
else if (newTimeBlockStart > newTimeBlockEnd)
return false;
// assuming that there' no null blocks within existingTimeBlocks
// and all blocks within existingTimeBlocks are valid ones
foreach (var block in existingTimeBlocks) {
//TODO: check edges: < or <=; > or >=
if ((newTimeBlockStart < block.EndTime) && (newTimeBlockEnd > block.StartTime))
return true; // overlap found
}
return false; // no overlap found
}
答案 2 :(得分:0)
假设您的时间块包含开始日期和结束日期,请使用OverlapsWith函数...
public class TimeBlock
{
public DateTime EndTime {get;set;}
public DateTime StartTime {get;set;}
public bool OverlapsWith(TimeBlock other)
{
return (StartTime <= other.StartTime && EndTime >= other.StartTime)
|| (StartTime <= other.EndTime && EndTime >= other.EndTime);
}
}
然后在你的功能......
var myBlock = new TimeBlock{ EndTime = newTimeBlockEnd, StartTime = newTimeBlockStart};
if(existingTimeBlocks.Any(x => x.OverlapsWith(myBlock)))
// ...your code