undefined undefined - 1 year ago 146
C# Question

IEnumerable and order

I've got a question about the order in

, does not matter).

As we know, 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.
) with indexation support?

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

UPD: So,
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?
? Both of them contain
method (even is not implemented in the former one.) Any suggestions?

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

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

Answer Source

IEnumerable makes no guarantees about ordering, but the implementations that use IEnumerable 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download