Vivian River
Vivian River

Reputation: 32390

How does .net determine the order for the "foreach" loop?

When I use the foreach statement in C# .net, how does .net determine in what order to process the elements in the collection?

Upvotes: 1

Views: 341

Answers (2)

Achim
Achim

Reputation: 15702

It's using the IEnumerable and IEnumerator interfaces. They a providing the values one after another, so .Net does not have to care about ordering. It's processing the values just in the order as they are delivered.

Upvotes: 1

Reed Copsey
Reed Copsey

Reputation: 564413

When you use foreach, the object which implements IEnumerable or IEnumerable<T> is "iterated". The order is determined by the object's implementation of IEnumerable.

Any class can customize the order in which this occurs. With a List<T>, for example, it's in the list's order (by index). However, some classes such as Dictionary<T,U> do not guarantee an order at all - only that each item will get enumerated through one time, as providing an ordering guarantee in that case would dramatically hamper performance.

Upvotes: 10

Related Questions