I have got a question about the order in IEnumerable.

As far as I am aware, iterating through IEnumerable is pseudo-code can be written in the following way:

while (enumerable.HasNext())
{
    object obj = enumerable.Current;
    ...
}

Now, assume, that one needs to operate on a sorted collection. Can IEnumerable be used in this case or is it better to try other means (i.e. IList) with indexation support?

In other words: does the contract of IEnumerable make any guarantees about the order in general?

So, IEnumerable is not a proper mean for a generic interface that guarantees ordering. The new question is what interface or class should be used for an immutable collection with order? ReadonlyCollection? IList? Both of them contain Add() method (even is not implemented in the former one).

My own thoughts: IEnumerable does not provide any guarantees about the ordering. The correct implementation could return same elements in different order in different enumerations (consider an SQL query)

I am aware of LINQ First(), but if IEnumerable does not say a word about it's ordering, this extension is pretty useless.


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.


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.


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