如何从日期列表中找到最近和更大的?

时间:2012-04-25 10:52:13

标签: c#

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

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

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

提前致谢!

4 个答案:

答案 0 :(得分:3)

这不会吗?

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()

答案 1 :(得分:1)

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

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

答案 2 :(得分:0)

怎么样

var startDateList = ClassForDBCalls.ActivityLISTByOutingID(iOutingID);

oActivityNearestLarger = startDateList
    .Where(a => a.StartDate > dtStartDate)
    .OrderBy(a => a.StartDate).First();

答案 3 :(得分:0)

我认为您还需要检查最大日期是否晚于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;