Reputation: 5226
I do have a Stack and a List. I need to copy all the items from list to stack without using loops i.e for, foreach.. etc.
Is there recommended way of doing it?
Upvotes: 15
Views: 20675
Reputation: 5
In java 1.8 Stack has a predefined method call addAll - Item will be push on to the stack
stack.addAll(list);
Upvotes: -1
Reputation: 12351
If you want to Pop the items in the same order as they appear in your list, then reverse your list before you create the stack from it.
var myStack = new Stack<MyObjectType>(myList.Reverse());
Upvotes: 5
Reputation: 120480
new Stack<T>(myListOfT)
Alternatively (without loops)
myStack.Push(myList[0]);
myStack.Push(myList[1]);
myStack.Push(myList[2]);
myStack.Push(myList[3]);
...
It's going to get pretty tedious. What's wrong with loops?
Upvotes: 0
Reputation: 19175
You can create a stack from anything that is IEnumerable
var myStack = new Stack<MyObjectType>(myList);
See MSDN: http://msdn.microsoft.com/en-us/library/76atxd68.aspx
However, the stack constructor will be using a loop internally, you just don't see it.
Upvotes: 36