2011-04-12 38 views
3

.NET在迭代集合时如何确定项目的顺序?C#针对集合的foreach迭代规则

例如:

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 
} 

我可以放心地使用foreachList?其他类型的收藏呢?

+1

你见过这样的:http://stackoverflow.com/questions/678162/sort-order-when-using-foreach-on-an-array-list-etc – 2011-04-12 08:45:40

+0

你的权利,我没有找到它(投票)。 – Xaqron 2011-04-12 11:21:27

回答

4

.NET并不能决定它 - 类实现IEnumerable决定它是如何正在做。对于从索引0到最后一个的List。对于Dictionary,它取决于我认为的密钥的哈希值。

List索引是基于0的,所以你可以这样做:

for (int i = 0; i < myList.Count; i++) 
{ 
    string item = myList[i]; // This is the order I need 
} 

是相同的结果foreach。但是,如果你想明确它,那么只要坚持for循环。没有错。

+0

,当然,如果你想要一个不同的顺序,你可以自由地扩展这个类并覆盖这个方法。 – Unsliced 2011-04-12 08:55:44

2

我相信foreach从第一个索引处开始,直到列表中的最后一项。

你可以安全地使用foreach,虽然我认为它比i = 1慢一点; i < myList.count方法。

另外,我会说你通常开始在索引0例如:

for (int i = 0; i < myList.Count -1 ; i++) 
{ 
string item = myList[i]; // This is the order I need 
} 
0

按照您的建议,通用列表将按添加顺序列举。其他Enumerator的实现可能会有所不同,如果它的重要性可以考虑SortedList。

1

foreach很好。如果您正在寻找性能(例如数字计算器),您应该只查看循环内部的工作方式。

1

不用担心,使用foreach。

 
list myList = new List(); 

myList.Add("a"); 
myList.Add("b"); 
myList.Add("c"); 

foreach (string item in myList) 
{ 
    // It's in right order! a -> b -> c ! 
}