I was wondering about the order that a foreach loop in C# loops through a System.Collections.Generic.List<T>
object.
I found another question about the same topic, but I do not feel that it answers my question to my satisfaction.
Someone states that no order is defined. But as someone else states, the order it traverses an array is fixed (from 0 to Length-1). 8.8.4 The foreach statement
It was also said that the same holds for any standard classes with an order (e.g. List<T>
). I can not find any documentation to back that up. So for all I know it might work like that now, but maybe in the next .NET version it will be different (even though it might be unlikely).
I have also looked at the List(t).Enumerator
documentation without luck.
Another related question states that for Java, it is specifically mentioned in the documentation:
List.iterator()
returns an iterator over the elements in this list
in proper sequence."
I am looking for something like that in the C# documentation.
Thanks in advance.
Edit: Thank you for all you for all your answers (amazing how fast I got so many replies). What I understand from all the answers is that List<T>
does always iterate in the order of its indexing. But I still would like to see a clear peace of documentation stating this, similar to the Java documentation on List
.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…