The way I've written this feels clunky. Particularly, it feels like I shouldn't need to have both a 'dateToCheck' and 'selectedDate' variables.
The objective is to find the Date in a list that is the closest to today (inclusive), with a preference for dates in the future.
The list is guaranteed to be passed in, in descending order.
The list can contain dates in the future...all the way to anytime in the past. Or just dates in the future. Or just today. Or just dates in the past. Anything...
Here is my working version:
Public Shared Function GetClosetDateToToday(lstOrderedDates As List(Of Date)) As Date ' Select the closest Delivery date to TODAY (inclusive) from the list of Ordered dates If lstOrderedDates.Count > 1 Then Dim dateToCheck = lstOrderedDates.ElementAt(1) Dim selectedDate = lstOrderedDates.ElementAt(0) For i = 1 To lstOrderedDates.Count - 1 If dateToCheck < Date.Now.Date Then Exit For End If If dateToCheck >= Date.Now.Date Then selectedDate = dateToCheck End If If i + 1 < lstOrderedDates.Count Then dateToCheck = lstOrderedDates.ElementAt(i + 1) End If Next i Return selectedDate ElseIf lstOrderedDates.Count = 1 Then Return lstOrderedDates.First() End If Return Nothing End Function
Is there a better way?