找到最近的下一个小时

本文关键字:下一个 小时 最近 | 更新日期: 2023-09-27 18:11:33

嗨,谁能告诉我如何用c#找到最近的时间

string target='13:10';
List<string> hours = ['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), 
                   };
    }
}

我已经试过了,实际上我得到了12:10作为结果,但是你明白了。