Generic List enumerator order [Vance Morrison]

“Is the order returned by the List<T> enumerator guaranteed to be the same as looping through with a for loop?”

Since foreach is actually defined in terms of looping over the ‘MoveNext’ operation of the enumerator, foreach is guaranteed to be equivalent to doing the enumeration by hand regardless of the implementation of the enumerator.

In the case of list, MoveNext is defined to walk in the list in order (The list is logically an array and you are traversing it from 0 to Count).

for enumerable types a foreach statement.....

foreach (AType aVar in aEnumerable) {
BODY
}

.... is defined to be

IEnumerator enumerator = aEnumerable.GetEnumerator();
while (enumerator.MoveNext())
{
aType aVar = (aType)enumerator.Current;
BODY
}

So by definition the enumerator is guaranteed to iterate in the same order as the foreach.