简体   繁体   中英

Finding closest date in a datetime list

I have been using this code to find the closest date in a list that is before the input date. However I found a bug recently that crashes the code when the input date is the same as the first date in the list.

allDates is a list of dates eg. 1/1/2015, 5/1/2015, 10/1/2015

inputDate is the date that the user selects

var closestDate = allDates.Where(x => x < inputDate).DefaultIfEmpty().Max();

When I tried selecting the first date in the list eg, 1/1/2015 the closest date comes out empty

Also right now if I select a date in the list, eg if the list contains 5/1/2015 and i select 5/1/2015, it does not select 5/1/2015 but select the earlier date in the list, right now I did a dirty workaround by reducing all the date in the list's date by 1

To fix the second issue use <= instead of <a .

var closestDate = allDates
  .Where(x => x <= inputDate)
  .DefaultIfEmpty()
  .Max();

Could the first issue be an invalid inputDate ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM