Generic List enumerator order [Vance Morrison]

Generic List enumerator order [Vance Morrison]

  • Comments 1

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

  • I'm thinking that should read, "The list is logically an array and you are traversing it from 0 to Count-1". Those off-by-one errors are nasty!

Page 1 of 1 (1 items)