列出元组日期时间



我有一个变量List< Tuple< DateTime, double>> myList .
给定一个datetime,希望它返回前面的Tuple使用Linq datetime
例如,if "2013-Feb-08 21:34:00"提供,想要查看列表中日期时间在此timestamp之前的最后一个元组。

我如何使用Linq执行此操作?

编辑:
myList.Where(t => t.Item1 <timestamp(。最后((;>
解决了我的问题。与性能相比,哪个在性能
方面更好myList.TakeWhile(t => t.Item1 <timestamp(。最后((;>

使用 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];
var result = myList.OrderByDescending(t => t.Item1)
  .SkipWhile(t => t.Item1 > timestamp)
  .First();

为了获得最佳性能,根本不应该使用 LINQ。二叉搜索提供的性能 O(log n( 与 LINQ 可以提供的 O(n( 相媲美。

为您的类型创建比较器:

public class MyListComparer : IComparer<Tuple<DateTime, double>> {
  public int Compare(Tuple<DateTime, double> x, Tuple<DateTime, double> y) {
    return x.Item1.CompareTo(y.Item1);
  }
}

将比较器与BinarySearch方法一起使用:

int idx = myList.BinarySearch(new Tuple<DateTime, double>(new DateTime(2013,2,8,21,34,0), 0), new MyListComparer());
if (idx < 0) {
  idx = (~idx) - 1;
}
Tuple<DateTime, double> item = myList[idx];

myList.Where(t => t.Item1 <datetime(。OrderByDescending(t> t.Item1(。最后((;

最新更新