Reputation: 16007
Will the elements in myList
always be visited in the same order with a For Each
loop (assuming I don't alter the list)?
Dim myList As New List(Of MyElement)
....
For Each myElem As MyElement In myList
' yadda yadda yadda
Next
Upvotes: 0
Views: 271
Reputation: 1500515
Yes, they will always be in the natural list order.
For Each
is basically a language constructor around calling GetEnumerator()
/MoveNext()
/Current
, so the ordering is up to the List(Of T)
class - which does indeed preserve ordering.
To give a contrasting example, if you iterate over the key/value pairs in a Dictionary(Of TKey, Of TValue)
then the order isn't guaranteed and adding or removing one entry is allowed to change the entire ordering.
Upvotes: 6