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?
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).
Yes. The foreach loop will iterate through the list in the order provided by the iterator() method.
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 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.
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.
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