I have few stacks in my code that I use to keep track of my logical location. At certain times I need to duplicate the stacks, but I can’t seem to clone them in such way that it preserves the order. I only need shallow duplication (references, not object).
What would be the proper way to do it? Or should I use some other sort of stacks?
I saw this post Stack Clone Problem: .NET Bug or Expected Behaviour?, but not sure how to setup clone method for the Stack<T> class.
You can write this as an extension method as
This is necessary because the
Stack<T>constructor that we are using here isStack<T>(IEnumerable<T> source)and of course when you iterate over theIEnumerable<T>implementation for aStack<T>it is going to repeatedly pop items from the stack thus feeding them to you in reverse of the order that you want them to go onto the new stack. Therefore, doing this process twice will result in the stack being in the correct order.Alternatively:
Again, we have to walk the stack in the reverse order from the output from iterating over the stack.
I doubt there is a performance difference between these two methods.