How to Enqueue a list of items in C#?

Joe Cabezas picture Joe Cabezas · Oct 2, 2013 · Viewed 20.2k times · Source

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

Answer

Ahmed KRAIEM picture Ahmed KRAIEM · Oct 2, 2013
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!