.NET foreach语句是否保证以与构建集合的顺序相同的顺序迭代集合? [英] Is the .NET foreach statement guaranteed to iterate a collection in the same order in which it was built?
问题描述
一个同事使用for循环来迭代一个列表,在他写的一些C#代码中,并留下了评论,没有使用For Each因为我不知道它按顺序迭代,谁知道Microsoft将做什么。例如,假设我们有一个像这样建立的List:
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]);
}
而不是这样:
foreach (var item in someList)
{
System.Diagnostics.Debug.WriteLine(item);
}
我想他恐怕这些项目可能会以不同的顺序出现添加到收藏。我认为他有点偏执,但在技术上,文档没有说明迭代的集合的顺序。 foreach语句有可能以除了从最低限制到最高限制之外的任何顺序遍历数组或集合对象吗?
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?
推荐答案
您的问题是关于列表< T>
,它保持顺序。
Your question is regarding a List<T>
, which does maintain order.
foreach做任何事情。它只是询问提供给它的枚举器的对象,它可以做任何事情。
foreach, alone, is not guaranteed to do anything. It just asks the object provided for its enumerator, which could do anything, potentially.
这篇关于.NET foreach语句是否保证以与构建集合的顺序相同的顺序迭代集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!