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.
IEnumerable is an interface defining a single method GetEnumerator() that returns an IEnumerator interface. It is the base interface for all non-generic collections that can be enumerated. This works for read-only access to a collection that implements that IEnumerable can be used with a foreach statement.
The List<> class does guarantee ordering - things will be retained in the list in the order you add them, including duplicates, unless you explicitly sort the list.
IEnumerable is conceptually faster than List because of the deferred execution. Deferred execution makes IEnumerable faster because it only gets the data when needed. Contrary to Lists having the data in-memory all the time.
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.
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