开发者

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

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 w开发者_开发知识库ork?

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?


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);


I suspect what is going to mess you up is the Distinct. This will likely reorder the results by manufacturer to produce the distinct results. I'd likely just iterate through the list until I had three distinct manufacturers.

The selection will retain the ordering but the remarks on Distinct indicate that it returns an unordered result set and that it is implementation dependent. To be sure, I wouldn't rely on it retaining the ordering and simply do it using the 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;
        }
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜