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?
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With