C# 下个小时找到最近的

C# 下个小时找到最近的,c#,datetime,C#,Datetime,大家好,有谁能告诉我如何找到最接近c的时间吗# string target='13:10'; 列出时间=['4:30','12:10','15:3','22:00']; 结果必须是15:3 任何帮助都将不胜感激:)由于您的列表已排序,您只需选择大于或等于目标的第一个元素: string result = hours.First(x => TimeSpan.Parse(x) >= TimeSpan.Parse(target)); 我想您可以编写一个LINQ查询 假设您实际上有一个D

大家好,有谁能告诉我如何找到最接近c的时间吗#

string target='13:10';
列出时间=['4:30','12:10','15:3','22:00'];
结果必须是15:3


任何帮助都将不胜感激:)

由于您的列表已排序,您只需选择大于或等于目标的第一个元素:

string result = hours.First(x => TimeSpan.Parse(x) >= TimeSpan.Parse(target));

我想您可以编写一个LINQ查询

假设您实际上有一个
DateTime
数组,而不是
string

class Program
{
    static void Main()
    {
        var target = new DateTime(2011, 10, 17, 13, 10, 0);
        IEnumerable<DateTime> choices = GetChoices();
        var closest = choices.OrderBy(c => Math.Abs(target.Subtract(c).TotalMinutes)).First();
        Console.WriteLine(closest);
    }

    private static IEnumerable<DateTime> GetChoices()
    {
        return new[]
                   {
                       new DateTime(2011, 10, 17, 4, 30, 0), 
                       new DateTime(2011, 10, 17, 12, 10, 0), 
                       new DateTime(2011, 10, 17, 15, 30, 0), 
                       new DateTime(2011, 10, 17, 22, 00, 0), 
                   };
    }
}
类程序
{
静态void Main()
{
var目标=新日期时间(2011,10,17,13,10,0);
IEnumerable choices=GetChoices();
var restact=choices.OrderBy(c=>Math.Abs(target.Subtract(c.TotalMinutes)).First();
控制台写入线(最近);
}
私有静态IEnumerable GetChoices()
{
返回新的[]
{
新的日期时间(2011、10、17、4、30、0),
新日期时间(2011、10、17、12、10、0),
新的日期时间(2011、10、17、15、30、0),
新的日期时间(2011、10、17、22、00、0),
};
}
}

我已经尝试过了,实际上我得到了
12:10
,但你明白了。

在这里发布的内容是为了寻找一个剪切粘贴解决方案,它会出现。编写真正的C代码开始。并丢失字符串,使用DateTime。这没有真正的意义,最近的时间应该是12:10,而不是15:30。
15:3
不是什么,但如果你的意思是
15:30
,那么这不是最近的时间,
12:10
是。需要更多的规则。此外,此代码不会编译。字符串是
双引号用C#分隔,字符是单引号
@cap俘-下个小时提到的标题。回答得好,但你真的应该使用
FirstOrDefault
,否则将target更改为
23:10
。但在我的情况下,我们总是有价值观,因此它完全符合我的需要。谢谢
class Program
{
    static void Main()
    {
        var target = new DateTime(2011, 10, 17, 13, 10, 0);
        IEnumerable<DateTime> choices = GetChoices();
        var closest = choices.OrderBy(c => Math.Abs(target.Subtract(c).TotalMinutes)).First();
        Console.WriteLine(closest);
    }

    private static IEnumerable<DateTime> GetChoices()
    {
        return new[]
                   {
                       new DateTime(2011, 10, 17, 4, 30, 0), 
                       new DateTime(2011, 10, 17, 12, 10, 0), 
                       new DateTime(2011, 10, 17, 15, 30, 0), 
                       new DateTime(2011, 10, 17, 22, 00, 0), 
                   };
    }
}