Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In LINQ, do projections off an IOrderedEnumerable<T> preserve the order?

Tags:

c#

.net

linq

If I have an IOrderedEnumberable<Car>, I sort it and then do a projecting query...

is the order preserved in the projection?

For example, does this scenario work?

IOrderedEnumberable<Car> allCarsOrderedFastestToSlowest = 
            GetAllCars()
                  .OrderByDescending(car=>car.TopSpeed);

var top3FastestCarManufacturers =
            allCarsOrderedFastestToSlowest
                  .Select(car=>car.Manufacturer)
                  .Distinct()
                  .Take(3);

Does the name of the top3FastestCarManufacturers variable convey the meaning of what has really happened in the code?

like image 760
Neil Fenwick Avatar asked Dec 04 '10 15:12

Neil Fenwick


People also ask

Does LINQ preserve order?

Therefore, by default, PLINQ does not preserve the order of the source sequence. In this regard, PLINQ resembles LINQ to SQL, but is unlike LINQ to Objects, which does preserve ordering.

Does ToList preserve order?

The simple answer is no, ToList will just loop over the source enumerable and keep the same order. List<T> guarantees order, so calling ToList on it won't change it.


1 Answers

The documentation for the Distinct method doesn't say anything about whether the order is preserved or not. This is probably because it depends on the underlying implementation of the source.

You can use grouping to get the desired result, by getting the fastest car from each manufacturer, and then get the three fastest from that:

var topThreeFastestCarManufacturers =
  GetAllCars()
  .GroupBy(c => c.Manufacturer)
  .Select(g => g.OrderByDescending(c => c.TopSpeed).First())
  .OrderByDescending(c => c.TopSpeed)
  .Take(3);
like image 163
Guffa Avatar answered Oct 05 '22 11:10

Guffa