Does LINQ execute predictions with an IOrderedEnumerable <T> save order?
If I have an IOrderedEnumberable<Car> , I sort it and then do a projection query ...
- the order stored in the projection?
For example, does this script work?
IOrderedEnumberable<Car> allCarsOrderedFastestToSlowest = GetAllCars() .OrderByDescending(car=>car.TopSpeed); var top3FastestCarManufacturers = allCarsOrderedFastestToSlowest .Select(car=>car.Manufacturer) .Distinct() .Take(3); Does the variable name top3FastestCarManufacturers what really happened in the code?
The documentation for the Distinct method says nothing about saving the order or not. This is likely due to the fact that it depends on the underlying implementation of the source.
You can use the grouping to get the desired result, getting the fastest car from each manufacturer, and then get the three fastest of them:
var topThreeFastestCarManufacturers = GetAllCars() .GroupBy(c => c.Manufacturer) .Select(g => g.OrderByDescending(c => c.TopSpeed).First()) .OrderByDescending(c => c.TopSpeed) .Take(3); I suspect it will ruin you. This is likely to alter the results made by the manufacturer to obtain excellent results. I would most likely go through the list until I had three different manufacturers.
The selection will keep order, but the notes on Distinct indicate that it returns an unordered result set and that it is implementation dependent. Of course, I would not rely on this, keeping order and just doing it with iteration.
var top3 = new List<string>(); foreach (var manufacturer in allCarsOrderedFastestToSlowest .Select(car=>car.Manufacturer)) { if (!top3.Contains(manufacturer)) { top3.Add(manufacturer); if (top3.Count == 3) { break; } } }