【问题标题】:How to find nearest DateTime keys of DateTime in SortedDictionary?如何在 SortedDictionary 中找到最近的 DateTime 键?
【发布时间】:2016-07-19 12:19:27
【问题描述】:

我有一个 DateTime 和 double _historicalValues 的 SortedDictionary,以及一个传递 DateTime date 的方法 HistoricalValueHistoricalValue 必须返回与 date 最接近的 _historicalValues 中日期时间的对应双精度值。有没有一种很好的方法可以利用 SortedDictionary 来找到最近的 DateTime?

我认为有一种更好的方法来完成这项任务,因为我的方法根本不利用 SortedDictionary,并且必须首先迭代整个集合以评估日期差异。

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];
}

【问题讨论】:

  • 这些历史价值相差多远?可能值得按年、按月、按周将整个事情切碎。给你一个小得多的工作组,并且可以加快速度。
  • 您不需要排序字典,因为您不使用实际的对而只使用结果。在这种情况下,常规字典可以正常工作,如果您希望它存储更少,因为存储 uint,doublelong,double 之类的对,然后只需将日期时间转换为相应的数据类型 ex。 date.ToBinary().
  • 如果它是历史日期的简短列表,只需对其进行迭代,如果您想针对大型集合进行优化,您可以拥有一个排序列表/数组并执行带有变体的二进制搜索。或者,您可能可以创建(或找到)一个堆实现。您的 find 应该执行插入(但不插入项目)并找到两个相邻的值。
  • @Bauss 这正是我问是否有任何方法可以利用 SortedDictionary 的原因。
  • 见这里:stackoverflow.com/questions/12412869/…。请注意,只有当您的字典很大时才应该打扰。否则只需遍历(已经排序的)键数组并与目标日期进行比较。

标签: c# datetime dictionary


【解决方案1】:

我会使用这个答案中提到的 MinBy:enter link description here

然后像这样使用它:

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

【讨论】:

  • 非常感谢 R00st3r,我也遇到过类似的问题,这真的很有帮助!
猜你喜欢
  • 2013-12-26
  • 2023-03-10
  • 2012-07-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多