42

Using lists I use

List<int> list = new List<int>();
list.AddRange(otherList);

How to do this using a Queue?, this Collection does not have a AddRange Method.

Queue<int> q = new Queue<int>();
q.AddRange(otherList); //does not exists
Krimson
  • 7,386
  • 11
  • 60
  • 97
Joe Cabezas
  • 1,397
  • 3
  • 15
  • 21
  • 3
    Is the answer basically "You can at construction, but there is no optimized AddRange equivalent other than calling Enqueue one-by-one." ? – billpg Jun 11 '18 at 16:09

3 Answers3

42
otherList.ForEach(o => q.Enqueue(o));

You can also use this extension method:

    public static void AddRange<T>(this Queue<T> queue, IEnumerable<T> enu) {
        foreach (T obj in enu)
            queue.Enqueue(obj);
    }

    Queue<int> q = new Queue<int>();
    q.AddRange(otherList); //Work!
Boris Sokolov
  • 1,723
  • 4
  • 23
  • 38
Ahmed KRAIEM
  • 10,267
  • 4
  • 30
  • 33
22

Queue has a constructor that takes in an ICollection. You can pass your list into the queue to initialize it with the same elements:

var queue = new Queue<T>(list); 

in your case use as follows

Queue<int> ques = new Queue<int>(otherList);
Thilina H
  • 5,754
  • 6
  • 26
  • 56
5

You can initialize the queue list:

Queue<int> q = new Queue<int>(otherList);
LarsTech
  • 80,625
  • 14
  • 153
  • 225