A coworker used a for loop to iterate a List in some C# code he wrote and left the comment, "did't use For Each because I wasn't sure it iterates in order. Who knows what Microsoft will do." For example, suppose we have a List built up like this:
var someList = new List<string>();
my coworker used something like this:
for (int i = 0; i < someList.Count; i++)
instead of this:
foreach (var item in someList)
I guess he's afraid the items might come out in a different order than they were added to the collection. I think he's being a bit paranoid, but technically, the documentation does not state the order in which the collection is iterated. Is it possible for a foreach statement to traverse an array or collection object in any order other than from lowest bound to highest?
Your question is regarding a
List<T>, which does maintain order.
foreach, alone, is not guaranteed to do anything. It just asks the object provided for its enumerator, which could do anything, potentially.
It depends on the collection:
List<T>it's guaranteed to be insertion order. (That's assuming just
Addcalls as shown. If you insert elements into the list at particular places, they'd get returned at the right pointas you'd expect.) Basically it's the same order as you'd get by taking
Dictionary<TKey, TValue>there's no guaranteed ordering.
SortedList<TKey, TValue>(and the like) it'll be in key comparison order - that's the point of the type.
To specifically answer the question, "foreach" returns the order that the .GetEnumerator() returns. For lists, it's the order that you added things to the end. For dictionaries, it's probably the order of the buckets where things were assigned.