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

最大の日付が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 に答える
0

どうですか

var startDateList = ClassForDBCalls.ActivityLISTByOutingID(iOutingID);

oActivityNearestLarger = startDateList
    .Where(a => a.StartDate > dtStartDate)
    .OrderBy(a => a.StartDate).First();
于 2012-04-25T11:01:58.250 に答える