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 anIOrderedEnumerable
? - 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?
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>
: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 implementIOrderedEnumerable<T>
interface, it's only simpleIEnumerable<T>
. Ordered collection is now source of iterator, but not iterator itself.