我有一個GridView,它有三列名稱,開始日期和結束日期。 時間範圍按排序順序。意思GridView默認按開始日期排序。 用戶想要插入一個名稱,開始日期和結束日期的新行。 如果新開始日期和新結束日期之間的時間跨度與其他行(可能多於一行)的時間跨度相交。這些行將被刪除,並且這個新記錄將被插入到GridView中。如果與任何時間跨度沒有交集,那麼只需將它添加到GridView。如何找出時間範圍與C#中給定時間範圍的交集?
如果已經寫了下面的代碼來找出兩個日期之間的交集(數據類型是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。 所以我的疑問是有沒有更好的方式來做到這一點在複雜性較低或更簡單的方式。
先決條件:所有時間範圍最初是互斥的,意味着行之間沒有交集。
你的問題是什麼?如果您詢問您的代碼,我不確定它是否可行,我相信您可以用更少的if-else塊編寫相同的邏輯。使用嵌套的if塊,使用<= and > =運算符,這應該有助於降低複雜性。此外,請考慮單元測試此方法 –