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?
.NET doesn't decide it - the class implementing IEnumerable
decides how it is being done. For List
that is from index 0 to the last one. For Dictionary
it depends on the hash value of the key I think.
List
indexes are 0 based, so you can do this:
for (int i = 0; i < myList.Count; i++)
{
string item = myList[i]; // This is the order I need
}
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.
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:
for (int i = 0; i < myList.Count -1 ; i++)
{
string item = myList[i]; // This is the order I need
}
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 ) .
Don't worry, use 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 ! }
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.
精彩评论