0

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

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

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

4 回答 4

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()
于 2012-04-25T10:58:08.000 回答
1

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

var result = oActivityByStartDateList.Where(x => x.StartDate > dtStartDate).OrderBy(x => x.StartDate).First();
于 2012-04-25T10:59:46.897 回答
0

怎么样

var startDateList = ClassForDBCalls.ActivityLISTByOutingID(iOutingID);

oActivityNearestLarger = startDateList
    .Where(a => a.StartDate > dtStartDate)
    .OrderBy(a => a.StartDate).First();
于 2012-04-25T11:01:58.250 回答
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;
于 2012-04-25T11:04:10.030 回答