当前位置: 动力学知识库 > 问答 > 编程问答 >

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?

网友答案:

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.

网友答案:

It depends on the collection:

  • For List<T> it's guaranteed to be insertion order. (That's assuming just Add calls as shown. If you insert elements into the list at particular places, they'd get returned at the right pointas you'd expect.) Basically it's the same order as you'd get by taking list[0], list[1], list[2] etc.
  • For Dictionary<TKey, TValue> there's no guaranteed ordering.
  • For SortedList<TKey, TValue> (and the like) it'll be in key comparison order - that's the point of the type.
  • Arrays always come out in element order.
网友答案:

To specifically answer the question, "foreach" returns the order that the .GetEnumerator() returns. For lists, it's the order that you added things to the end. For dictionaries, it's probably the order of the buckets where things were assigned.

分享给朋友:
您可能感兴趣的文章:
随机阅读: