我有一个字典,其中键是DateTime。我需要在字典中找到最接近给定日期时间的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
}
我打算在字典中循环,但这真的是最好的方式吗?&gt;任何人都有更好的解决方案吗?
由于
答案 0 :(得分:1)
这应该有效。 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
}
}
}
答案 1 :(得分:0)
如果您可以将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));