Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the .NET foreach statement guaranteed to iterate a collection in the same order in which it was built?

A coworker used a for loop to iterate a List in some C# code he wrote and left the comment, "did't use For Each because I wasn't sure it iterates in order. Who knows what Microsoft will do." For example, suppose we have a List built up like this:

var someList = new List<string>();

someList.Add("one");
someList.Add("two");
someList.Add("three");

my coworker used something like this:

for (int i = 0; i < someList.Count; i++)    
{
    System.Diagnostics.Debug.WriteLine(someList[i]);
}

instead of this:

foreach (var item in someList)              
{
    System.Diagnostics.Debug.WriteLine(item);
}

I guess he's afraid the items might come out in a different order than they were added to the collection. I think he's being a bit paranoid, but technically, the documentation does not state the order in which the collection is iterated. Is it possible for a foreach statement to traverse an array or collection object in any order other than from lowest bound to highest?

like image 329
raven Avatar asked Mar 04 '09 21:03

raven


People also ask

Is foreach always in order?

All replies. Yes. An (IList) is ordered, and iterating will iterate from the first item to the last, in order inserted (assuming you always inserted at the end of the list as opposed to somewhere else, depending on the methods you used).

Does foreach loop in order?

Yes. The foreach loop will iterate through the list in the order provided by the iterator() method.

Does foreach keep order C#?

Yes. you can do that. For arrays, it will access elements in order. For other types (IEnumerable, or having GetEnumerator), it accesses elements in the order provided, through alternating MoveNext and Current calls.

How does a foreach loop work in C#?

How Does It Work? The foreach loop in C# uses the 'in' keyword to iterate over the iterable item. The in keyword selects an item from the collection for the iteration and stores it in a variable called the loop variable, and the value of the loop variable changes in every iteration.


1 Answers

Your question is regarding a List<T>, which does maintain order.

foreach, alone, is not guaranteed to do anything. It just asks the object provided for its enumerator, which could do anything, potentially.

like image 195
Rex M Avatar answered Nov 16 '22 01:11

Rex M