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?
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);
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.
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