2011-04-12 19 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 ! 
}