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?
We use stack or queue instead of arrays/lists when we want the elements in a specific order i.e. in the order we put them (queue) or in the reverse order (stack). Queues and stacks are dynamic while arrays are static. So when we require dynamic memory we use queue or stack over arrays.
Now declare a string array and use the CopyTo() method to copy. string[] arr = new string[20]; list1. CopyTo(arr); Let us see the complete code to copy a list into a one-dimensional array.
Use the AddRange() method to append a second list to an existing list. list1. AddRange(list2);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With