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
一起使用吗?那其他类型的收藏呢?     
已邀请:
.NET不能决定它-实现
IEnumerable
的类决定了它是如何完成的。对于
List
,它从索引0到最后一个索引。对于
Dictionary
,它取决于我认为的键的哈希值。
List
索引基于0,因此您可以执行以下操作:
for (int i = 0; i < myList.Count; i++)
{
    string item = myList[i]; // This is the order I need
}
foreach
的结果相同。但是,如果您想对其进行明确说明,则只需坚持使用for循环即可。没有错。     
我相信foreach从第一个索引开始,然后逐步执行直到列表中的最后一个项目。 您可以安全地使用foreach,尽管我认为它比i = 1的速度慢一些;我
for (int i = 0; i < myList.Count -1 ; i++)
{   
 string item = myList[i]; // This is the order I need
}
    
foreach很好。如果您正在寻找性能(例如,数字紧缩器),则应该只研究循环工作的内部原理。     
不用担心,使用foreach。 list myList = new List(); myList.Add(\“ a \”); myList.Add(\“ b \”); myList.Add(\“ c \”); foreach(myList中的字符串项) {     //顺序正确! a-> b-> c! }     
根据您的建议,通用列表将按添加顺序枚举。 Enumerator的其他实现可能有所不同。如果重要,则可以考虑使用SortedList。     

要回复问题请先登录注册