Question

Can I assume that the IEnumerator I get from an IList (by calling the GetEnumerator method from the IEnumerable interface) will give me the items in the order of the list?

Was it helpful?

Solution

You can't, because IList is an interface, and an implementation can enumerate items in any order. For instance, I could implemenent WeirdList : IList, and have it enumerate items in any way, including non-deterministically. If you use a List(T) on the other hand, it guarantees to enumerate items in the order they are stored in the list.

Edit: That being said, as many others point out, most implementations will follow the semantics of List(T). Although that wasn't what you asked ;)

OTHER TIPS

The enumerator should give you access to the objects inside the list relative to their position in memory which would be the same as using the indexer of the list going from 0 to Length < 1 in a for loop.

Edit: I answered specifically in regards to the .NET framework classes that implement IList, should any other person implement these interfaces their actual implementation could be just about anything. So it depends on implementer.

Yes, it will do exactly that, for any decent implementation of IList at least. A good IList should always enumerate its elements in the same order as in which the list is indexed.

List<int> list = new List<int> { 1, 1, 2, 3, 5, 8 };

IEnumerator<int> enumtor = list.GetEnumerator();
while (enumtor.MoveNext())
{
    Console.Write(enumtor.Current);
}

Prints 112358.

This will depend on the implementation of the IList

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top