c# - Will IOrderedEnumerable.Select() retain element order? -


in c#, using select() project elements of iorderedenumerable retain element order?

  • if so, how come returns ienumerable, , not iorderedenumerable?
  • if not, how can achieve (other using foreach)?

note question not duplicate of this one - have select() clause, wihtout distinct().

edit

yes, linq objects. btw, answer different if in fact quering sql db?

select not change elements order. streaming operator (msdn), means processes source elements in order of source , yields projected elements 1 one.

so, if doing projection of ordered source, projected results retain order of source elements.


one more thing - may wondering why result not implement iorderedenumerable<t>:

int[] items = { 2, 3, 1, 8, 5 }; ienumerable<int> query = items.orderby(i => i).select(i => i); bool isordered = query iorderedenumerable<int>; // false 

it's because select operator returns new iterator object (whereselectarrayiterator in case) reads items source collection (orderedenumerable in case) 1 one, projects item, , returns projection. new iterator object not implement iorderedenumerable<t> interface, it's simple ienumerable<t>. ordered collection source of iterator, not iterator itself.


Comments