Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will IOrderedEnumerable.Select() retain element order?

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?

like image 595
bavaza Avatar asked Jul 15 '13 09:07

bavaza


1 Answers

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.

like image 105
Sergey Berezovskiy Avatar answered Oct 14 '22 08:10

Sergey Berezovskiy