Find the closest time from a list of times

var closestTime = listOfTimes.OrderBy(t => Math.Abs((t - fileCreateTime).Ticks))
                             .First();

If you don’t want the performance overhead of the OrderBy call then you could use something like the MinBy extension method from MoreLINQ instead:

var closestTime = listOfTimes.MinBy(t => Math.Abs((t - fileCreateTime).Ticks));

Something like this:

DateTime fileDate, closestDate;
ArrayList theDates;
long min = long.MaxValue;

foreach (DateTime date in theDates)
 if (Math.Abs(date.Ticks - fileDate.Ticks) < min)
 {
   min = Math.Abs(date.Ticks - fileDate.Ticks);
   closestDate = date;
 }

Leave a Comment