Will IOrderedEnumerable.Select () keep the order of the elements?

In C # will Select() be used to project elements of the order IOrderedEnumerable of an element's persistence?

  • If so, how does it return IEnumerable , not IOrderedEnumerable ?
  • If not, how can I achieve this (other than using foreach )?

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

EDIT

Yes, this is LINQ to Objects. By the way, would the answer be different if I were really querying SQL DB?

+8
c # ienumerable iorderedenumerable
source share
1 answer

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

So, if you are designing an ordered source, the predicted results will preserve the order of the source elements.


One more thing - you might be wondering why the 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 

This is because the Select statement returns a new iterator object ( WhereSelectArrayIterator in this case), which reads the elements from the original collection ( OrderedEnumerable in this case) one by one, the project object and returns the projection. This new iterator object does not implement the IOrderedEnumerable<T> interface, it is just a simple IEnumerable<T> . An ordered collection is now the source of the iterator, but not the iterator itself.

+10
source share

All Articles