Queue

suggest change

Queue stores values in FIFO (first-in, first-out) order. Enqueue(T item) adds an element, and Dequeue() removes and returns the element that has been in the queue the longest. The generic version can hold a queue of strings:

First, add the namespace:

using System.Collections.Generic;

and use it:

Queue<string> queue = new Queue<string>();
queue.Enqueue("John");
queue.Enqueue("Paul");
queue.Enqueue("George");
queue.Enqueue("Ringo");

string dequeueValue;
dequeueValue = queue.Dequeue(); // return John
dequeueValue = queue.Dequeue(); // return Paul
dequeueValue = queue.Dequeue(); // return George
dequeueValue = queue.Dequeue(); // return Ringo

There is a non-generic version that stores object values. Product below stands for any reference type defined elsewhere. If both System.Collections and System.Collections.Generic are imported, write System.Collections.Queue so the name is not ambiguous.

The namespace is:

using System.Collections;

A non-generic queue:

Queue queue = new Queue();
queue.Enqueue("Hello World"); // string
queue.Enqueue(5); // int
queue.Enqueue(1d); // double
queue.Enqueue(true); // bool
queue.Enqueue(new Product()); // Product object

object dequeueValue;
dequeueValue = queue.Dequeue(); // return Hello World (string)
dequeueValue = queue.Dequeue(); // return 5 (int)
dequeueValue = queue.Dequeue(); // return 1d (double)
dequeueValue = queue.Dequeue(); // return true (bool)
dequeueValue = queue.Dequeue(); // return Product (Product type)

Peek() returns the object at the beginning of the queue without removing it. Enumerating the queue also leaves the elements in place:

Queue<int> queue = new Queue<int>();
queue.Enqueue(10);
queue.Enqueue(20);
queue.Enqueue(30);
queue.Enqueue(40);
queue.Enqueue(50);

foreach (int element in queue)
{
    Console.WriteLine(element);
}

The output (without removing):

10
20
30
40
50

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents