Find Closest next hour
Hi can anyone say how to find the closest hour with c#
string target='13:10';
List<string> hours 开发者_如何学C= ['4:30', '12:10', '15:3', '22:00'];
The result must be 15:3
Any help would be appreciated:)
Since your list is sorted, you can simply select the first element that is greater than or equal to the target:
string result = hours.First(x => TimeSpan.Parse(x) >= TimeSpan.Parse(target));
You can write a LINQ query, I suppose.
Assuming you actually have an array of DateTime
rather than 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),
};
}
}
I've tried this out and actually I get 12:10
as the result, but you get the idea.
精彩评论