2014-02-10 99 views
0

我有一個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。 所以我的疑問是有沒有更好的方式來做到這一點在複雜性較低或更簡單的方式。

先決條件:所有時間範圍最初是互斥的,意味着行之間沒有交集。

+1

你的問題是什麼?如果您詢問您的代碼,我不確定它是否可行,我相信您可以用更少的if-else塊編寫相同的邏輯。使用嵌套的if塊,使用<= and > =運算符,這應該有助於降低複雜性。此外,請考慮單元測試此方法 –

回答

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 

這最後一個條件告訴你他們notdon't intersect(雙重否定)。 所以他們相交。

邊界條件不包括在內。將</>替換爲<=/>=,反之亦然。

+1

另外,不要允許構建非法範圍對象,確保只有一種創建方法,並且在其中應該定義開始時間和結束時間,並且結束時間應該大於開始時間 –

+0

真的很好的解釋!一次顯示邏輯和代碼:) – statue

+0

解釋得很好,如何將這個邏輯有效地應用於一組時間範圍? – user3264676