locked
Iteration Order using a foreach loop RRS feed

  • Question

  • I have a List<T> and am iterating it using a foreach loop. The order of the items in the list is very important. Is it safe to use a foreach loop or should I use a fornext loop.

    There are some guys saying that foreach does not iterate in the same order as the order of items collection.

    Can some one from Microsoft please clarify this?

    Thanks.
    Monday, December 14, 2009 7:22 AM

Answers

  • It depends on the collection u are using. The foreach does nothing more then iterate through the iterator of that collection. With List<T> u are safe to assume the order will be kept assuming u only use the Add method. A Dictionary<TKey, TValue> is not guaranteed to keep his order but a SortedList<TKey, TValue> is guaranteed to be ordered based on TKey.
    • Proposed as answer by André Werlang Monday, December 14, 2009 12:18 PM
    • Marked as answer by eryang Monday, December 21, 2009 2:07 AM
    Monday, December 14, 2009 8:17 AM