Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing Queue or Stack with default values?

Tags:

stack

c#

queue

You can Initialize a list with pre-placed values:

List<int> L1 = new List<int> {1, 2, 3};

is there an equivalent of above for Queue? My idea was :

Queue<int> Q1 = new Queue<int> {1, 2, 3};

which doesn't work. Is there any workaround?

Is

Queue<int> Q1 = new Queue<int>();
Q1.Enqueue(1);
Q1.Enqueue(2);
Q1.Enqueue(3);

the only valid solution?

like image 480
thkang Avatar asked Jan 01 '13 06:01

thkang


2 Answers

Use the constructor Queue<T> Constructor (IEnumerable<T>)

Queue<int> Q1 = new Queue<int>(new[] { 1, 2, 3 });

Or

List<int> list = new List<int>{1, 2, 3 };
Queue<int> Q1 = new Queue<int>(list);
like image 153
Habib Avatar answered Oct 19 '22 20:10

Habib


See: http://blogs.msdn.com/b/madst/archive/2006/10/10/what-is-a-collection_3f00_.aspx and particularly:

The meaning of this new syntax is simply to create an instance of MyNames using its no-arg constructor (constructor arguments can be supplied if necessary) and call its Add method with each of the strings.

and

The resulting language design is a “pattern based” approach. We rely on users using a particular name for their methods in a way that is not checked by the compiler when they write it. If they go and change the name of Add to AddPair in one assembly, the compiler won’t complain about that, but instead about a collection initializer sitting somewhere else suddenly missing an overload to call.

A queue doesnt support the Add method and hence therefore can't be initialized with the short expression style syntax. This is really a choice by design. Luckily, you can pass a collection to the Queue's constructor.

like image 4
Polity Avatar answered Oct 19 '22 20:10

Polity