.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
一起使用吗?那么其他类型的收藏呢?
答案 0 :(得分: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循环。没错。
答案 1 :(得分:2)
我相信foreach从第一个索引开始,直到列表中的最后一个项目为止。
你可以安全地使用foreach,虽然我认为它比for i = 1慢一点;我&lt; myList.count方法。
另外,我会说你通常从索引0开始。例如:
for (int i = 0; i < myList.Count -1 ; i++)
{
string item = myList[i]; // This is the order I need
}
答案 2 :(得分:1)
foreach很好。如果您正在寻找性能(例如数字计算器),您应该只查看循环如何工作的内部结构。
答案 3 :(得分: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 ! }
答案 4 :(得分:0)
如您所建议的那样,通用列表将按添加顺序进行枚举。 Enumerator的其他实现可能会有所不同,如果它很重要,您可以考虑使用SortedList。