Question

In C#, will using Select() to project the elements of an IOrderedEnumerable retain element order?

  • If so, how come it returns an IEnumerable, and not an IOrderedEnumerable?
  • If not, how can I achieve this (other than using foreach)?

Note that this question is NOT a duplicate of this one - I only have a Select() clause, without Distinct().

EDIT

Yes, it is LINQ to Objects. BTW, would the answer be any different if I were in fact quering some SQL DB?

Was it helpful?

Solution

Select does not change elements order. It is a streaming operator (MSDN), which means it processes source elements in the order of source and yields projected elements one by one.

So, if you are doing projection of ordered source, projected results will retain order of source elements.


One more thing - you may be wondering why result does not implement IOrderedEnumerable<T>:

int[] items = { 2, 3, 1, 8, 5 };
IEnumerable<int> query = items.OrderBy(i => i).Select(i => i);
bool isOrdered = query is IOrderedEnumerable<int>; // false

It's because Select operator returns new iterator object (WhereSelectArrayIterator in this case) which reads items from source collection (OrderedEnumerable in this case) one by one, projects item, and returns projection. This new iterator object does not implement IOrderedEnumerable<T> interface, it's only simple IEnumerable<T>. Ordered collection is now source of iterator, but not iterator itself.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top