1

Does the generic List guarantee the order of its items when adding and iterating the values?

If so, is it in the definition of the type or is it just an assumption on the usual behavior?

Updated:

It looks like the order is kept for now; there is no trace of this in the official documentation, therefore I assume it might change in the future and will not be in the definition of List.

Is there another simple collection that guarantees the order? (Excluding Stack/Queue which are specialized for other uses)

Stefano d'Antonio
  • 5,874
  • 3
  • 32
  • 45
  • possible duplicate of [Does List guarantee insertion order?](http://stackoverflow.com/questions/1043039/does-listt-guarantee-insertion-order) – Rubens Farias May 29 '15 at 19:31
  • The other question considers also insertion and it states you might get "odd results". I just want to make sure they stay in the same order if I just use the Add method and the iteration. – Stefano d'Antonio May 29 '15 at 19:37
  • 2
    [List.Add](http://msdn.microsoft.com/en-us/library/3wcytfd1.aspx): "The object to be added _to the end_ of the List"; or consider [Does a List guarantee that items will be returned in the order they were added?](http://stackoverflow.com/questions/453006/does-a-listt-guarantee-that-items-will-be-returned-in-the-order-they-were-adde) question – Rubens Farias May 29 '15 at 19:39

2 Answers2

1

It looks like it's a safe assumption.

Although, for critical applications (defence/finance), it might be worth using a LinkedList or sub-classing the List to make it future-proof in case a new framework changes the implementation.

The GetEnumerator will always return the first element in the List, but there is no written guarantee that the next element must be the second in the List.

Stefano d'Antonio
  • 5,874
  • 3
  • 32
  • 45
  • 1
    "but there is no written guarantee that the next element must be the second in the List" - absolutely; if anything, it could be said to be strongly implied, given that "MoveNext passes the end of the collection" at some point, which is only meaningful if (at least at the last item in the list) the enumerator pointer movement happens in the general direction of indices in the list. (At the very least, it also guarantees that the last item in the list is enumerated last.) I agree it is not very explicitly described. – O. R. Mapper Jun 06 '15 at 11:55
-1

List<T> will maintain the order that you placed items into the list, however, other code could modify the order before you iterate over it. Depending on your use, you may consider using Queue<T> https://msdn.microsoft.com/en-us/library/7977ey2c(v=vs.110).aspx

solidau
  • 4,021
  • 3
  • 24
  • 45