Find the closest time from a list of times

后端 未结 11 774
眼角桃花
眼角桃花 2020-12-02 23:48

So, here\'s the scenario. I have a file with a created time, and I want to choose a time from a list of times that that file\'s created time is closest or equal too...what w

相关标签:
11条回答
  • 2020-12-03 00:02
    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));
    
    0 讨论(0)
  • 2020-12-03 00:03
    var closestTime = (from t in listOfTimes
                       orderby (t - fileInfo.CreationTime).Duration()
                       select t).First();
    
    0 讨论(0)
  • 2020-12-03 00:05

    Not an answer, but a question regarding the various LINQ solutions proposed above. How efficient is LINQ? I have not written any "real" programs with LINQ yet, so I'm not sure on the performance.

    In this example, the "listOfTimes" collection implies that we have already iterated over some file system based objects to gather the times. Would it have been more efficient to do the analysis during the iteration instead of later in LINQ? I recognize that these solutions may be more "elegant" or nicely abstract the "collection as database" idea, but I tend to choose efficiency (must be readable though) over elagance in my programming. Just wondering if the cost of LINQ might outweigh the elegance here?

    0 讨论(0)
  • 2020-12-03 00:05
    var creationTimes = new [] {DateTime.Now.AddDays(-1), DateTime.Now.AddDays(-2)};
    FileInfo fi = new FileInfo("C:/test.xml");
    var closestTime = creationTimes
        .OrderBy(c => Math.Abs(c.Subtract(fi.CreationTime).Days))
        .First();
    
    0 讨论(0)
  • 2020-12-03 00:06

    How often will you be doing this with the same list of times? If you're only doing it once, the fastest way is probably to just scan through the list and keep track of the closest time you've seen yet. When/if you encounter a time that's closer, replace the "closest" with that closer time.

    If you're doing it very often, you'd probably want to sort the list, then use a binary search.

    0 讨论(0)
  • 2020-12-03 00:07

    The accepted answer is completely wrong. What you want is something like this:

      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;
        }
      }
    
    0 讨论(0)
提交回复
热议问题