如何从日期列表中查找最近和较大的日期

本文关键字:日期 最近 列表 查找 | 更新日期: 2023-09-27 18:32:23

给定开始日期,如何从列表中找到更大和最近的开始日期?

这是我的代码,但我获取最近的代码的方法似乎不正确:

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;
        }
    }
}

提前感谢!

如何从日期列表中查找最近和较大的日期

这不行吗?

Activity nearestToStart = 
    lassForDBCalls.ActivityLISTByOutingID(iOutingID)
    .OrderBy(a => a.StartDate)
    .FirstOrDefault(a => a.StartDate >= myStartDate)

还是我错过了什么?

对不起,刚刚看到第一次尝试有多愚蠢

Activity nearestToStart = 
    lassForDBCalls.ActivityLISTByOutingID(iOutingID)
    .Where(a => a.StartDate >= myStartDate)
    .OrderBy(a => a.StartDate)
    .FirstOrDefault()

您可以过滤列表以查找大于 dtStartDate 的日期,然后对其进行排序并采用第一个日期,即较大且最近的开始日期

var result = oActivityByStartDateList.Where(x => x.StartDate > dtStartDate).OrderBy(x => x.StartDate).First();

怎么样

var startDateList = ClassForDBCalls.ActivityLISTByOutingID(iOutingID);
oActivityNearestLarger = startDateList
    .Where(a => a.StartDate > dtStartDate)
    .OrderBy(a => a.StartDate).First();

我认为您还需要检查最大的日期是否晚于 datetime.now。"最近"将给出与今天最近的日期,即使它早于今天。

DateTime nearest = oActivityByStartDateList.OrderBy(q => Math.Abs((q.StartDate - DateTime.Now).TotalMilliseconds)).First().StartDate;
     DateTime largest = oActivityByStartDateList.Where(p => p.StartDate.CompareTo(DateTime.Now) > 0).OrderByDescending(p => p.StartDate).First().StartDate;