Is it safe to assume that two itterations over the same collection will return the objects in the same order? Obviously, it is assumed that the collection has not otherwise been changed.
"The order in which foreach traverses the elements of an array, is as follows: For single-dimensional arrays elements are traversed in increasing index order, starting with index 0 and ending with index Length – 1.
Answers. Yes. An (IList) is ordered, and iterating will iterate from the first item to the last, in order inserted (assuming you always inserted at the end of the list as opposed to somewhere else, depending on the methods you used).
It depends on the collection type. For most collections, the answer is "Yes".
However, this is not guaranteed. The docs of a collection type should specify whether or not it does, but as most do, that detail is generally over looked. However, if it is not stable, it would be a tremendous oversight if the docs didn't mention that.
Short answer - yes.
Obviously, though, the order of the items in the collection may not be exactly as they were inserted, depending on the type of collection (a dictionary, for example).
But you will get the same results each time you iterate over a single, unmodified collection using a foreach loop.
You can't guarantee this unless you know the concrete implementation of the class you're iterating over.
Collections that have a defined element order (e.g. List<T>
) will enumerate in a stable order.
For collections where the state of the object doesn't change it's highly likely that elements will come back in the same order, e.g. Dictionary<K,V>
, although this not guaranteed by the specification.
As an example of where this would not be the case, you could imagine a hashtable based dictionary implementation that compacts or resizes the table asynchronously. Such an implementation would not guarantee a stable iteration order.
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