从列表中查找最接近的时间

Nic*_*ayo 20 c# comparison

所以,这是场景.我有一个创建时间的文件,我想从文件创建时间最接近或相等的时间列表中选择一个时间......最好的方法是什么?

Luk*_*keH 49

var closestTime = listOfTimes.OrderBy(t => Math.Abs((t - fileCreateTime).Ticks))
                             .First();
Run Code Online (Sandbox Code Playgroud)

如果您不想要OrderBy调用的性能开销,那么您可以使用类似MinBy扩展方法的内容MoreLINQ:

var closestTime = listOfTimes.MinBy(t => Math.Abs((t - fileCreateTime).Ticks));
Run Code Online (Sandbox Code Playgroud)

  • 更好的答案 (2认同)
  • 我很生气,这不是选定的答案. (2认同)

Kev*_*vin 8

接受的答案是完全错误的.你想要的是这样的:

  DateTime fileDate, closestDate;
  List<DateTime> theDates;

  fileDate = DateTime.Today;       //set to the file date
  theDates = new List<DateTime>(); //load the date list, obviously

  long min = Math.Abs(fileDate.Ticks - theDates[0].Ticks);
  long diff;
  foreach (DateTime date in theDates)
  {
    diff = Math.Abs(fileDate.Ticks - date.Ticks);
    if (diff < min)
    {
      min = diff;
      closestDate = date;
    }
  }
Run Code Online (Sandbox Code Playgroud)


luv*_*ere 7

像这样的东西:

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;
 }
Run Code Online (Sandbox Code Playgroud)

  • 这个答案是完全错误的.`millisecond`属性每秒从0到999.如果文件是在12:00:00.001创建的,则此方法将显示6:55:32.005,因为它比12:01:01.500更接近. (4认同)

Tho*_*que 6

var closestTime = (from t in listOfTimes
                   orderby (t - fileInfo.CreationTime).Duration()
                   select t).First();
Run Code Online (Sandbox Code Playgroud)


Jer*_*fin 5

您多久会使用相同的时间列表执行此操作?如果您只进行一次,最快的方法可能就是扫描列表并跟踪您最近看到的时间.当/如果您遇到更接近的时间,请将"最接近的"替换为更接近的时间.

如果你经常这样做,你可能想要对列表进行排序,然后使用二进制搜索.