隨着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