user132748
user132748

Reputation:

stack.ToList() – order of elements?

When using the .ToList() extension method on a Stack<T>, is the result the same as popping each element and adding to a new list (reverse of what was pushed)?

If so, is this because it really is iterating over each element, or does it store the elements in reverse internally and slip the array into a new List<T>?

Upvotes: 21

Views: 9379

Answers (2)

Matti Virkkunen
Matti Virkkunen

Reputation: 65126

Stack itself does not have a ToList method, it's the extension method from the Enumerable class. As those extension methods only deal with IEnumerable<T>, it's safe to assume that ToList iterates over the items of the stack to create the new list (or at least acts exactly as if it would - the Enumerable methods sometimes test the type of the argument and use an optimized implementation).

Interestingly the documentation does not seem to directly state which order the stack is enumerated in, but the example code does show an order and the examples are part of the documentation. Also, in practice changing the iteration order would break so much code that it would be way too risky to change now.

I also checked with Reflector; Stack<T> stores its items in an array with the bottommost element at index 0, but its Enumerator iterates the array in reverse order. Therefore the first element that comes out of the iterator is the top of the stack.

Upvotes: 20

Jon Skeet
Jon Skeet

Reputation: 1500805

ToList will iterate in the same order as if you did this:

foreach (T item in stack)

The docs for GetEnumerator() don't explicitly state the order as far as I can tell, but the example shows that it will iterate as if it were popping. So if you push 1, 2, 3, 4, 5 then ToList will give you 5, 4, 3, 2, 1.

Upvotes: 12

Related Questions