Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the order of objects returned by FOREACH stable?

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.

like image 561
Metro Avatar asked Oct 03 '08 14:10

Metro


People also ask

Does foreach have an order?

"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.

Does foreach preserve order C#?

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).


3 Answers

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.

like image 137
James Curran Avatar answered Oct 03 '22 15:10

James Curran


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.

like image 35
NM. Avatar answered Oct 03 '22 17:10

NM.


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.

like image 25
mancaus Avatar answered Oct 03 '22 17:10

mancaus