0

因此,我在 LINQ 查询中仅选择一个元素(cars类型为Car[]):

Car selectedCar = (
    from x
    in cars
    where x.Location * direction > location * direction
    orderby x.Location * direction
    select x)
    .FirstOrDefault();

这基本上是一个 O(n log n) 操作(因为orderby)。我可以通过使用 LINQ 来降低约 30% 的性能损失,但是当它很容易成为 O(n) 循环时,我不能让它成为 O(n log n)。有没有办法保留 LINQ,但减少操作顺序?

4

2 回答 2

5

聚合应该可以解决问题:

Car selectedCar = cars
 .Where(x => x.Location * direction > location * direction)
 .Aggregate((a, b) => (a.Location * direction < b.Location * direction) ? a : b);

我还没有检查过这段代码是否真的有效,所以要小心。

于 2013-08-27T06:31:13.383 回答
-1

试试这个:

Car selectedCar = cars.Where(x=>x.Location * direction > location * direction).Min(x=>x.Location * direction);
于 2013-08-27T06:14:02.773 回答