问题描述
我想知道,在C#中的foreach循环遍历顺序 System.Collections.Generic.List< T>
对象
I was wondering about the order that a foreach loop in C# loops through a System.Collections.Generic.List<T>
object.
我发现another关于同一主题的问题,但我不认为它回答我的问题让我满意的。
I found another question about the same topic, but I do not feel that it answers my question to my satisfaction.
有人指出,没有订单被定义。但作为其他人的状态,它横穿阵列的顺序是固定的(从0到长度-1)。
Someone states that no order is defined. But as someone else states, the order it traverses an array is fixed (from 0 to Length-1). 8.8.4 The foreach statement
也有人说,同样适用于任何标准班用命令(例如列表&LT; T&GT;
)。我找不到任何文件来支持这件事。因此,对于所有我知道它可能工作一样,现在,但也许在未来的.NET版本会有所不同(尽管它可能是不可能的)。
It was also said that the same holds for any standard classes with an order (e.g. List<T>
). I can not find any documentation to back that up. So for all I know it might work like that now, but maybe in the next .NET version it will be different (even though it might be unlikely).
我也看了看文档没有运气。
I have also looked at the List(t).Enumerator
documentation without luck.
指出,对于Java,它是专门提及文档:
Another related question states that for Java, it is specifically mentioned in the documentation:
List.iterator()
在返回的元素的迭代器在此列表
以正确的顺序。
我要寻找的C#文档中类似的东西。
I am looking for something like that in the C# documentation.
先谢谢了。
编辑:谢谢你为所有的答案(我惊人的速度有多快了那么多的回复)。我从所有的答案不解的是,列表&LT; T&GT;
并一直在其索引的顺序进行迭代。但我还是想看到的文档清晰的说明和平这一点,类似的。
Thank you for all you for all your answers (amazing how fast I got so many replies). What I understand from all the answers is that List<T>
does always iterate in the order of its indexing. But I still would like to see a clear peace of documentation stating this, similar to the Java documentation on List
.
推荐答案
基本上它是到的IEnumerator
实施 - 但对于一个列表&LT; T&GT ;
它总是会走在了名单的自然顺序,即相同的顺序索引:列表[0]
,列表[1]
,列表[2]
等。
Basically it's up to the IEnumerator
implementation - but for a List<T>
it will always go in the natural order of the list, i.e. the same order as the indexer: list[0]
, list[1]
, list[2]
etc.
我不相信它的明确记载 - 至少,我还没有发现这样的文件 - 但我认为你可以把它当作保证。该订货的任何变化将毫无意义的突破各种code的。事实上,我很惊讶地看到的任何实现的IList&LT; T&GT;
这违背了这一点。诚然,这将是很高兴看到它专门记录...
I don't believe it's explicitly documented - at least, I haven't found such documentation - but I think you can treat it as guaranteed. Any change to that ordering would pointlessly break all kinds of code. In fact, I'd be surprised to see any implementation of IList<T>
which disobeyed this. Admittedly it would be nice to see it specifically documented...
这篇关于按照什么顺序做了C#for each循环遍历目录&LT; T&GT ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!