Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Enqueue a list of items in C#?

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
like image 390
Joe Cabezas Avatar asked Oct 02 '13 15:10

Joe Cabezas


People also ask

How do I create a queue list?

typedef struct queue_t { int data; /* the date in the queue, can be anything, not only an int */ struct queue_t* next; /* pointer to the next in the queue */ } queue_t; And then another one is the list of 20 queues: queue_t *list_of_queues[20];

What is dequeue and enqueue?

In programming terms, putting items in the queue is called enqueue, and removing items from the queue is called dequeue.

What is enqueue method?

The Queue. Enqueue() method in C# is used to add an object to the end of the Queue.

What is enqueue and dequeue in C#?

Enqueue adds an element to the end of the Queue. Dequeue removes the oldest element from the start of the Queue. Peek returns the oldest element that is at the start of the Queue but does not remove it from the Queue. The capacity of a Queue is the number of elements the Queue can hold.


3 Answers

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!
like image 104
Ahmed KRAIEM Avatar answered Oct 02 '22 23:10

Ahmed KRAIEM


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);
like image 37
Thilina H Avatar answered Oct 02 '22 21:10

Thilina H


You can initialize the queue list:

Queue<int> q = new Queue<int>(otherList);
like image 34
LarsTech Avatar answered Oct 02 '22 21:10

LarsTech