2011-10-20 48 views
1

我遇到一些問題,試圖在Visual Basic .NET中設置子例程來檢查記錄數組,並刪除日期字段在當前日期之前的所有記錄。 這裏是我當前的代碼:VB.NET日期數組處理問題

Sub FutureDate() 
     Dim movefrom As Integer 
     For x As Integer = 0 To UBound(notifications) 

      If notifications(x).MeetingTime < Now.Date Then 'Finds first current/future date. 
       movefrom = x 
      End If 
     Next 
     Dim moveto As Integer = 0 
     For x As Integer = movefrom To UBound(notifications) 'Moves dates after this to beginning of array. 
      movefrom += 1 
      notifications(moveto) = notifications(movefrom) 
      moveto += 1 
     Next 
     ReDim Preserve notifications(moveto) 'Shortens the array to the correct length. 
    End Sub 

這個子被調用後,程序將顯示前三記錄在消息框中陣列(用於調試目的)英寸但是,當我運行該程序時,消息框從不顯示。這個問題絕對是問題所在,因爲註釋掉可以解決問題的路線,並且會顯示相應的消息,儘管第一個框中包含過去的日期。這是爲了通知/即將到來的會議系統,所以我顯然不希望包含已通過的日期。

記錄已按日期排序,所以在我看來,這應該做我想做的事情,即刪除過去的日期記錄,將其他所有內容移到數組的前面,然後刪除記錄被移出的最後空格。但是,我經常在這樣的事情上犯愚蠢的錯誤,所以外界的投入是非常感謝。任何你能給的幫助都會很棒。

謝謝。

+0

你有沒有試過使用LINQ?我認爲你想要完成的事情可能更容易使用linq完成。 –

+0

嗯謝謝你,我從來沒有考慮過這個選擇。這會讓事情變得更簡單。 – Aaron

+0

lambda表達式很棒。 – Yatrix

回答

1

這是一個班輪:

Sub FutureDate() 
    notifications = notifications.Where(Function(n) n.MeetingTime < Today).ToArray() 
End Sub 

但更好的設計是建立一個函數,返回新的數組:

Function FutureDate(ByVal items() As MyType) As MyType() 
    Return items.Where(Function(n) n.MeetingTime < Today).ToArray() 
End Function 

和甚至更好的去思考條款序列而不是陣列:

Function FutureDate(ByVal items As IEnumerable(Of MyType)) As IEnumerable(Of MyType) 
    Return items.Where(Function(n) n.MeetingTime < Today) 
End Function 
+0

愛的化身,男人。弗里曼4人生。 – Yatrix

0
DateTime[] futureDates = notifications.Where(n => n.MeetingTime > DateTime.Now).Select(n => n.MeetingTime).ToArray(); 

這應該工作,我想。如果不是,則非常相似。這應該僅返回比現在更晚的會議的日期。

希望這會有所幫助。