IEnumerable and order

IEnumerable/IEnumerable<T> makes no guarantees about ordering, but the implementations that use IEnumerable/IEnumerable<T>may or may not guarantee ordering.

For instance, if you enumerate List<T>, order is guaranteed, but if you enumerate HashSet<T> no such guarantee is provided, yet both will be enumerated using the IEnumerable<T> interface.


Perhaps you are looking for the IOrderedEnumerable interface? It is returned by extensions methods like OrderBy() and allow for subsequent sorting with ThenBy().


Implementation detail. IEnumerable will enumerate the item - how that is implemented is up to the implementation. MOST lists etc. run along their natural order (index 0 upward etc.).

does the contract of IEnumerable guarantee us some order in general case?

No, it guarantees enumeration only (every item one time etc.). IEnumerable has no guaranteed order because it is also usable on unordered items.

I know about LINQ First(), but if IEnumerable does not say a word about it's order, this extension is rather useless.

No, it is not, because you may have intrinsic order. You give SQL as example - the result is an IEnumerable, but if I have enforced ordering before (By using OrderBy()) then the IEnumerable is ordered per definition of LINQ. AsEnumerable().First() gets me then the first item by Order.