Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy items from list to stack without using loop

Tags:

stack

c#

list

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?

like image 512
Thaadikkaaran Avatar asked May 25 '11 10:05

Thaadikkaaran


People also ask

Why use a stack instead of a list?

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.

How do I copy a list in C#?

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.

How do I assign a value from one list to another in C#?

Use the AddRange() method to append a second list to an existing list. list1. AddRange(list2);


1 Answers

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.

like image 121
Colin Mackay Avatar answered Oct 13 '22 00:10

Colin Mackay