In C#, will using Select() to project the elements of an IOrderedEnumerable retain element order?
IEnumerable, and not an IOrderedEnumerable?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>:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With