stack.ToList() – order of elements?

非 Y 不嫁゛ 提交于 2019-12-08 14:46:35

问题


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




回答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.



来源:https://stackoverflow.com/questions/2628048/stack-tolist-order-of-elements

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!