Eric Hansen
Eric Hansen

Reputation: 1809

How to find nearest DateTime keys of DateTime in SortedDictionary?

I have a SortedDictionary of DateTime and double _historicalValues, and a method HistoricalValue which is passed a DateTime date. HistoricalValue must return the corresponding double for the DateTime in _historicalValues that is closest to date. Is there a nice way in which I can leverage a SortedDictionary in order to find the closest DateTime?

I think there is a better way to approach this task as my approach is something that doesn't leverage a SortedDictionary at all, and tediously has to iterate over the whole collection to evaluate the date differences first.

private readonly SortedDictionary<DateTime, double> _historicalValues;    

public double HistoricalValue(DateTime date)
{
    if (_historicalValues.ContainsKey(date))
        return _historicalValues[date];

    var closestDate = _historicalValues.Keys.OrderBy(
          t => Math.Abs((t - date).Ticks)).First();
    return _historicalValues[closestDate];
}

Upvotes: 2

Views: 760

Answers (1)

R00st3r
R00st3r

Reputation: 974

I would use the MinBy mentioned in this answer: enter link description here

And then use it like this:

return _historicalValues.MinBy(kvp => Math.Abs((kvp.Key - date).Ticks)).Value;

Upvotes: 1

Related Questions