我有一个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。因此,我怀疑是否有更好的方法,以较少的复杂性或更容易的方式来做到这一点。
前提条件:所有时间范围一开始都是相互排斥的,这意味着行之间没有交集。
发布于 2014-02-10 15:11:03
在这些情况下,两个集合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 do don't intersect (双重否定)。所以他们相交了。
排除边界条件。将</>替换为<=/>=,反之亦然。
https://stackoverflow.com/questions/21680520
复制相似问题