There is a collection in .Net used to manage values in a Queue
that uses the FIFO (first-in first-out) concept. The basics of queues is the method Enqueue(T item)
which is used to add elements in the queue and Dequeue()
which is used to get the first element and remove it from the queue. The generic version can be used like the following code for 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 of the type, which works with objects.
The namespace is:
using System.Collections;
Adn a code sample fo 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)
There is also a method called Peek() which returns the object at the beginning of the queue without removing it the elements.
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(i);
}
The output (without removing):
10
20
30
40
50