使LINQ选择O(n),只选择一个元素

Ham*_*asi 0 c# linq performance

所以,我只选择LINQ查询中的一个元素(cars类型Car[]):

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

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

Jul*_*ult 5

聚合应该做的伎俩:

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

我没有检查这段代码是否真的有用,所以要小心.