Initialize a queue or stack with default values?

You can initialize a list with preset values:

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

is there an equivalent above for the queue? My idea:

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

which does not work. Is there any workaround?

Is an

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

the only acceptable solution?

+7
source share
3 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); 
+14
source

try it

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

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

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

and

The resulting language design is a template-based approach. We rely on users using a specific name for their methods so that they are not checked by the compiler when they are written. If they go and change the name Add to AddPair in one assembly, the compiler will not complain about it, but instead there is suddenly no overload for calling the collection initializer somewhere else.

The queue does not support the Add method and therefore cannot be initialized with short expression style syntax. It really is a design choice. Fortunately, you can pass the collection to the queue constructor.

+1
source

All Articles