In an array of dates how to find closest previous date from a given date?
For example I have an array of 1000 dates for example 1-feb-2010,15-jan-1997,10-feb-2001,17-feb-2010 and so on....If date given is for exampl 15-feb-2010 I need to find closest previous date from given date. In this case correct answer should be 1-feb-2010. How to find this date? Thanx for help
SebastianPosted Feb 26, 2010, 6:35 PM
public DateTime? FindClosestDate(IEnumerable
{
DateTime? result = null;
var lowestDifference = TimeSpan.MaxValue;
foreach (var date in source)
{
if (date >= target)
continue;
var difference = target - date;
if (difference < lowestDifference)
{
lowestDifference = difference;
result = date;
}
}
return result;
}