简体   繁体   English

如何找到从数组到DateTime.Now的最接近的较大时间

[英]How to find closest bigger time from an array to DateTime.Now

I am trying to find closest bigger time to current time. 我正在尝试找到与当前时间最接近的更大时间。 This is the code that i have: 这是我的代码:

var busTimes = new string[]
    {
        "15:00",
        "16:00",
        "17:00",
        "18:00",
        "19:00",
        "20:00",
        "21:00"
        }
        .Select(x => DateTime.Parse(x))
        .ToList();

var now = DateTime.Now.TimeOfDay;

var closestTime = (from x in busTimes
                   where x.busTimes.TimeOfDay > now
                   orderby x.busTimes.TimeOfDay ascending
                   select x).First(); 

But I get this error: 但是我得到这个错误:

Error CS1061 'DateTime' does not contain a definition for 'busTimes' and no extension method 'busTimes' accepting a first argument of type 'DateTime' could be found (are you missing a using directive or an assembly reference?) 错误CS1061'DateTime'不包含'busTimes'的定义,并且找不到扩展方法'busTimes'接受类型为'DateTime'的第一个参数(您是否缺少using指令或程序集引用?)

How can i fix this? 我怎样才能解决这个问题?

x is a DateTime , like the error message said, there is no busTimes property on it. xDateTime ,如错误消息中所述,它上没有busTimes属性。

var closestTime = (from x in busTimes
    where x.TimeOfDay > now
    orderby x.TimeOfDay ascending
    select x).First(); 

Your query should be: 您的查询应为:

var closestTime = (from x in busTimes
        where x.TimeOfDay > now
        orderby x.TimeOfDay ascending
        select x).First(); 

As the x identifier represents a DateTime and a DateTime struct doesn't have a 'busTimes' property. 由于x标识符表示DateTimeDateTime结构没有'busTimes'属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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