.NET foreach 语句是否保证以与构建集合相同的顺序迭代集合? [英] Is the .NET foreach statement guaranteed to iterate a collection in the same order in which it was built?

查看:25
本文介绍了.NET foreach 语句是否保证以与构建集合相同的顺序迭代集合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一位同事在他编写的一些 C# 代码中使用 for 循环迭代 List 并留下评论,没有使用 For Each 因为我不确定它是否按顺序迭代.谁知道 Microsoft 会做什么."例如,假设我们有一个像这样构建的列表:

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?

推荐答案

你的问题是关于一个List,它确实维持秩序.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆