In what order does a C# for each loop iterate over a List<T>?
Basically it's up to the IEnumerator
implementation - but for a List<T>
it will always go in the natural order of the list, i.e. the same order as the indexer: list[0]
, list[1]
, list[2]
etc.
I don't believe it's explicitly documented - at least, I haven't found such documentation - but I think you can treat it as guaranteed. Any change to that ordering would pointlessly break all kinds of code. In fact, I'd be surprised to see any implementation of IList<T>
which disobeyed this. Admittedly it would be nice to see it specifically documented...
On Microsoft Reference Source page for List<T>
Enumerator it is explicitly stated that the iteration is done from 0 to Length-1:
internal Enumerator(List<T> list) {
this.list = list;
index = 0;
version = list._version;
current = default(T);
}
public bool MoveNext() {
List<T> localList = list;
if (version == localList._version && ((uint)index < (uint)localList._size))
{
current = localList._items[index];
index++;
return true;
}
return MoveNextRare();
}
Hope it's still relevant for somebody
In your link, the accepted answer states in C# Language Specification Version 3.0, page 240:
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. For multi-dimensional arrays, elements are traversed such that the indices of the rightmost dimension are increased first, then the next left dimension, and so on to the left. The following example prints out each value in a two-dimensional array, in element order:
using System; class Test { static void Main() { double[,] values = { {1.2, 2.3, 3.4, 4.5}, {5.6, 6.7, 7.8, 8.9} }; foreach (double elementValue in values) Console.Write("{0} ", elementValue); Console.WriteLine(); } }
The output produced is as follows: 1.2 2.3 3.4 4.5 5.6 6.7 7.8 8.9 In the example
int[] numbers = { 1, 3, 5, 7, 9 }; foreach (var n in numbers) Console.WriteLine(n); the type of n is inferred to be int, the element type of numbers.