随着MoreLinq MaxBy(可从的NuGet):
myList.Where(t => t.Item1 < timestamp).MaxBy(t => t.Item1);
或者(如果项目排序):
myList.TakeWhile(t => t.Item1 < timestamp).Last();
UPDATE(二进制搜索)写的比较器:
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];
使用[.OderByDescending](http://stackoverflow.com/questions/5344805/linq -orderby-descending-query) – spajce
我想要的元素可能不是orderby列表中的第一个元素。 – Chris
“last”,你的意思是列表中索引最高的项目,还是具有最高“DateTime”值的项目? – Guffa