给定开始日期,我如何从列表中找到较大和最近的开始日期?
这是我的代码,但我获取最近代码的方式似乎不正确:
Activity oActivityNearestLarger = null;
List<Activity> oActivityByStartDateList = ClassForDBCalls.ActivityLISTByOutingID(iOutingID)
.OrderBy(a => a.StartDate)
.ToList();
long lLeastTicksDifference = 0; // initialize
int iIndexOfTheNearestLargerActivity = 0;
for (int i = 0; i < oActivityByStartDateList.Count; i++)
{
// the start of the loop, set the lRecordTicksDifference
if (i == 0)
{
lLeastTicksDifference = Math.Abs(oActivityByStartDateList[0].StartDate.Value.Subtract(dtStartDate).Ticks);
}
long lCurrentTicksDifference = Math.Abs(oActivityByStartDateList[i].StartDate.Value.Subtract(dtStartDate).Ticks);
// get the larger, closest start datetime in the activities for the outing
if (oActivityByStartDateList[i].StartDate > dtStartDate)
{
// is the current activity startdate closer
// to the to be added startdate (is it the nearest to the datetime being added?)
if (lCurrentTicksDifference <= lLeastTicksDifference)
{
// if it has the least difference (meaning closer) store it for comparison in the next iteration
lLeastTicksDifference = lCurrentTicksDifference;
oActivityNearestLarger = oActivityByStartDateList[i];
// set the index to be used to determine the Activity previous to it
iIndexOfTheNearestLargerActivity = i;
}
}
}
提前致谢!