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
.
There is no concept of left-to-right or right-to-left evaluation in C, which is not to be confused with left-to-right and right-to-left associativity of operators: the expression f1() + f2() + f3() is parsed as (f1() + f2()) + f3() due to left-to-right associativity of operator+, but the function call to f3 may be ...
Note: The operators are listed in order of priority, group 1 having the highest priority and group 7 the lowest.
The || operator shall yield 1 if either of its operands compare unequal to 0; otherwise, it yields 0. The result has type int. 4 Unlike the bitwise | operator, the || operator guarantees left-to-right evaluation; there is a sequence point after the evaluation of the first operand.
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With