我有一个GridView,它有三列名称,开始日期和结束日期。 时间范围按排序顺序排列。意味着GridView默认按开始日期排序。 用户想要插入带有名称,开始日期和结束日期的新行。 如果新开始日期和新结束日期之间的时间跨度与其他行的任何其他(可能多于一行)时间跨度相交。这些行将被删除,这个新记录将插入到GridView中。如果没有任何时间跨度的交集,则只需将其添加到GridView。
如果已编写以下代码以找出两个日期之间的交集(数据类型为DateTime)。
public class DateTimeRange
{
public DateTime Start { get; set; }
public DateTime End { get; set; }
public bool Intersects(DateTimeRange test)
{
if (this.Start > this.End || test.Start > test.End)
return false;
//throw new InvalidDateRangeException();
if (this.Start == this.End || test.Start == test.End)
return false; // No actual date range
if (this.Start == test.Start || this.End == test.End)
return true; // If any set is the same time, then by default there must be some overlap.
if (this.Start < test.Start)
{
if (this.End > test.Start && this.End < test.End)
return true; // Condition 1
if (this.End > test.End)
return true; // Condition 3
}
else
{
if (test.End > this.Start && test.End < this.End)
return true; // Condition 2
if (test.End > this.End)
return true; // Condition 4
}
return false;
}
}
所以我打算逐行迭代GridView(逐个),存储与新recode相交的Rows索引。迭代后,我将删除这些索引的行并插入新的Recode。 所以我怀疑是否有更好的方法以更简单或更简单的方式做到这一点。
前提条件:所有时间范围最初互斥,表示行之间没有交集。
答案 0 :(得分:2)
在这些情况下,两组a和b不相交:
---|<--A-->|----------------
-------------|<--B-->|------
a.End < b.Start
--------------|<--A-->|-----
---|<--B-->|----------------
a.Start > b.End
因此,如果你将两种情况结合起来:
a.End < b.Start || a.Start > b.End
现在你可以否定它:
!(a.End < b.Start || a.Start > b.End)
要进行优化,请使用De Morgan获取:
a.End >= b.Start && a.Start <= b.End
最后一个条件告诉你他们not
做don't intersect
(双重否定)。
所以他们相交了。
不包括边境条件。将<
/ >
替换为<=
/ >=
,反之亦然,以反过来。