I'd like to know if I can 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.
What do you think?
I'd like to know if I can 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.
What do you think?
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
.
IEnumerable is just an interface, which any container (or even non container-like object) can implement to provide its contents, one item at a time.
The order in which these items are returns depend on the semantics of the underlying container. Although most container types have the concept of some order for its content, There is nothing that prevents a particular implementer if IEnumerator to return the items in a random order.
Edit: (Missed the IList part of the question)
IList implies a container with some concept of sequential and consistent order, lest its methods relying on an index would mean very little. So, yes!, an IList's enumerator SHOULD return the items in a prescribed order.
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 ;)
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.