从字典中找到 2 个日期时间之间的日期
本文关键字:日期 时间 之间 字典 | 更新日期: 2023-09-27 17:57:10
我有一本字典,其中键是日期时间。我需要在字典中找到最接近给定日期时间的 2 个条目。
所以,我有
Dictionary<DateTime, double> columnInfos = new Dictionary<DateTime, double>();
foreach (var activity in activities)
{
DateTime activityDate = activity.ActivityDateTime;
// Get the 2 entries in the columnInfos dict that activityDate falls between
}
我打算遍历字典,但这真的是最好的方法吗> 有人有更好的解决方案吗?
谢谢
如果可以将Dictionary<T, T>
更改为 SortedDictionary<T, T>
,则可以编写如下函数:
private List<DateTime> FallBetween(SortedDictionary<DateTime, double> columns, DateTime activityDate)
{
var keys = new List<DateTime>(columns.Keys);
int index = ~(keys.BinarySearch(activityDate));
var dates = new List<DateTime>();
try
{
dates.Add(keys[index]);
} catch { }
try
{
dates.Add(keys[index - 1]);
} catch { }
return dates;
}
并像这样称呼它:
SortedDictionary<DateTime, double> columnInfos = new SortedDictionary<DateTime, double>();
columnInfos.Add(DateTime.Now, 1);
columnInfos.Add(DateTime.Now.AddDays(-2), 2);
columnInfos.Add(DateTime.Now.AddDays(-4), 3);
columnInfos.Add(DateTime.Now.AddDays(2), 4);
columnInfos.Add(DateTime.Now.AddDays(4), 5);
// dates will return a list containing two dates.
// Now - 2 days and Now - 4 days.
var dates = FallBetween(columnInfos, DateTime.Now.AddDays(-3));
// date will return a list containing only one date
// because there is only one nearing neighbor.
var date = FallBetween(columnInfos, DateTime.Now.AddDays(30));
这应该有效。 index-1
和index+1
将是日期列表中的位置,该日期将立即小于和大于相关日期。
SortedDictionary<DateTime, double> columnInfos = new SortedDictionary<DateTime, double>();
List<KeyValuePair<DateTime, double>> columnInfosList = columnInfos.ToList();
foreach (var activity in activities)
{
DateTime activityDate = activity.ActivityDateTime;
for (int index = 1; index < columnInfosList.Count(); index++)
{
if (columnInfosList[index-1].Key < activityDate && columnInfosList[index+1].Key > activityDate)
{
// do something with columnInfos[index-1] and columnInfos[index+1] then break so you stop searching
}
}
}