C# foreach 集合的迭代规则
.NET 在迭代集合时如何决定项目的顺序?
例如:
list<string> myList = new List<string>();
myList.Add("a");
myList.Add("b");
myList.Add("c");
foreach (string item in myList)
{
// What's the order of items? a -> b -> c ?
}
我需要这个命令(访问集合成员):
for (int i = 1; i < myList.Count; i++)
{
string item = myList[i - 1]; // This is the order I need
}
我可以安全地使用 foreach
与 List
吗?其他类型的收藏又如何呢?
How .NET decides for order of items when iterating through collections ?
For example:
list<string> myList = new List<string>();
myList.Add("a");
myList.Add("b");
myList.Add("c");
foreach (string item in myList)
{
// What's the order of items? a -> b -> c ?
}
I need this order (accessing collection members):
for (int i = 1; i < myList.Count; i++)
{
string item = myList[i - 1]; // This is the order I need
}
Can I safely use foreach
with List
? What about other types of collections?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
别担心,使用foreach。
Don't worry, use foreach.
正如您所建议的,通用列表将按添加顺序进行枚举。 Enumerator 的其他实现可能有所不同,如果它很重要,您可以考虑 SortedList。
A generic List will enumerate in the order of addition, as you suggest. Other implementations of Enumerator may vary, If its important you could consider a SortedList.
.NET 不决定它 - 实现
IEnumerable
的类决定它是如何完成的。对于List
来说,它是从索引 0 到最后一个索引。对于Dictionary
,我认为它取决于键的哈希值。List
索引是从 0 开始的,因此您可以这样做:并且与
foreach
的结果相同。但是,如果您想明确说明这一点,那么只需坚持 for 循环即可。这没什么问题。.NET doesn't decide it - the class implementing
IEnumerable
decides how it is being done. ForList
that is from index 0 to the last one. ForDictionary
it depends on the hash value of the key I think.List
indexes are 0 based, so you can do this:and is the same result as
foreach
. However if you want to be explicit about it then just stick to the for loop. Nothing wrong with that.我相信 foreach 从第一个索引开始,然后一直走到列表中的最后一项。
你可以安全地使用 foreach 虽然我认为它比 for i=1; 慢一点;我< myList.count 方法。
另外,我想说你通常从索引 0 开始,例如:
I believe foreach starts at the first index and steps though until the last item in the list.
you can safely use foreach although I think it is a little slower than the for i=1; i < myList.count method.
Also, I would say you usually start at index 0. eg:
foreach 很好。如果您正在寻找性能(例如数字计算器),您应该只研究循环如何工作的内部结构。
foreach is fine . You should only look into the internals of how a loop works if you are looking for perfomance ( eg a number cruncher ) .