查找下一个最接近的日期 [英] Find next closest date

查看:164
本文介绍了查找下一个最接近的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我这是目前存储为一个字符串列表一些日期



例如:

 列表<串GT;日期=新的List<串GT;(); 
dates.Add(14年1月10日);
dates.Add(14年2月9日);
dates.Add(1/15/14);
dates.Add(14年2月3日);
dates.Add(14年2月15日);



(日期为 MM / DD / YY 格式)



我会考虑用户的输入(也有 MM / DD / YY 格式),但作为一个字符串。



现在,我想找到的是用户输入的日期之后的下一个最接近的数组中的日期。



例如,如果用户输入14年1月13日,输出应该是1/15/14
如果用户输入14年2月5日,那么下一个最接近的日期是14年2月9日
但是,如果用户输入晚于最后日期(14年3月1日,它仍然会返回在最后日期的日期阵列中,14年2月15日



我知道在某些时候你必须要转换成键入日期时间,但我想不出逻辑找到这样的日期。


解决方案

 清单<串GT;日期=新的List<串GT;(); 
dates.Add(14年1月10日);
dates.Add(14年2月9日);
dates.Add(1/15/14);
dates.Add(14年2月3日);
dates.Add(14年2月15日);

VAR allDates = dates.Select(DateTime.Parse).OrderBy(D => D).ToList();
变种inputDate = DateTime.Parse(14年1月13日);

VAR closestDate = inputDate> = allDates.Last()
? allDates.Last()
:inputDate< = allDates.First()
? allDates.First()
:allDates.First(D => d取代; = inputDate);



现在我只是解析字符串,但您需要单独处理。这是简单的纯LINQ,你可以去幻想和做的二进制搜索为好。


I have some dates which are currently stored as a list of strings.

For example:

List<string> dates = new List<string>();
dates.Add("1/10/14");
dates.Add("2/9/14");
dates.Add("1/15/14");
dates.Add("2/3/14");
dates.Add("2/15/14");

(The date is in mm/dd/yy format)

I will take a user's input (also in mm/dd/yy format), but as a string.

Now, I want to find the date in the array that is the next closest after the user input date.

For example, if the user enters "1/13/14", the output should be "1/15/14". If the user enters "2/5/14", then the next closest date is "2/9/14". But if the user enter a date that is later than the last date (say "3/1/14", it will STILL return the last date in the array which is "2/15/14")

I know at some point you have to convert to type DateTime, but I couldn't figure out the logic to find such date.

解决方案

List<string> dates = new List<string>();
            dates.Add("1/10/14");
            dates.Add("2/9/14");
            dates.Add("1/15/14");
            dates.Add("2/3/14");
            dates.Add("2/15/14");

            var allDates = dates.Select(DateTime.Parse).OrderBy(d=>d).ToList();
            var inputDate = DateTime.Parse("1/13/14");

            var closestDate = inputDate >= allDates.Last()
                ? allDates.Last()
                : inputDate <= allDates.First()
                    ? allDates.First()
                    : allDates.First(d => d >= inputDate);

For now I'm just parsing strings, but you should handle it separately. This is simple plain LINQ, you can go fancy and do binary search as well.

这篇关于查找下一个最接近的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆