使用MoreLinq MaxBy(可从 NuGet 获得):
myList.Where(t => t.Item1 < timestamp).MaxBy(t => t.Item1);
或者(如果项目已排序):
myList.TakeWhile(t => t.Item1 < timestamp).Last();
更新(使用二进制搜索)写入比较器:
public class MyComparer : IComparer<Tuple<DateTime, double>>
{
public int Compare(Tuple<DateTime, double> x, Tuple<DateTime, double> y)
{
return x.Item1.CompareTo(y.Item1);
}
}
然后搜索
int index = myList.BinarySearch(new Tuple<DateTime, double>(timestamp, 0),
new MyComparer());
if (index == 0)
// there is no items before timestamp
if (index > 0)
result = myList[index - 1]; // your item is previous
if (index < 0) // no tuple with date equal to timestamp
var nearestIndex = ~index;
if (nearestIndex > 0)
result = myList[nearestIndex - 1];