stack.ToList() in .NET - order of elements?

2019-06-15 07:27发布

问题:

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>?

回答1:

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, it's safe to assume that ToList iterates over the items of the stack to create the new list.

Updated: I 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.



回答2:

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.



标签: c# .net list stack