Page Stats
Visitor: 133
Queue Class
The System.Collections.Queue class follow the concept of First In First Out (FIFO), means that the item inserted first is processed first. To add an element is termed as Enqueue, and removal of an element from the queue is termed as 'Dequeue'. Concept of queue is used in printing when multiple users share same printer, if multiple request are send printer follow the concept of FIFO.

Enqueue() - Add element in Queue
To add an element in Queue use Enqueue() method, you can add elements of any datatype.
Example 1: Add elements in the Queue.
Queue qu = new Queue(); qu.Enqueue(10); qu.Enqueue(20); qu.Enqueue(30); qu.Enqueue("forty"); foreach(var item in qu) { Console.WriteLine(item); }
20
30
forty
Dequeue() - Removes element in Queue
Dequeue() removes and returns a first element from a queue. Calling Dequeue() method on empty queue will throw InvalidOperation exception.
Example 2: Delete element from the Queue.
Queue qu = new Queue(); qu.Enqueue(10); qu.Enqueue(20); qu.Enqueue(30); qu.Enqueue("forty"); Console.WriteLine("Number of elements in the Queue: {0}", qu.Count); while (qu.Count > 0) Console.WriteLine(qu.Dequeue()); Console.WriteLine("Number of elements in the Queue: {0}", qu.Count);
10
20
30
forty
Number of elements in the Queue: 0
Peek() Method - Queue
The Peek() method always returns the first element from a queue without removing it. Calling Peek() methods on an empty queue will throw a run time exception "InvalidOperationException".
Example 3: Display first element from the Queue.
Queue qu = new Queue(); qu.Enqueue(10); qu.Enqueue(20); qu.Enqueue(30); qu.Enqueue("forty"); Console.WriteLine("Number of elements in the Queue: {0}", qu.Count); Console.WriteLine(qu.Peek()); Console.WriteLine(qu.Peek()); Console.WriteLine("Number of elements in the Queue: {0}", qu.Count);
10
10
Number of elements in the Queue: 4
Contains() Method - Queue
The Contains() method checks whether an item exists in a queue or not. It returns true if the specified item exists, otherwise it returns false.
Example 4: Check element exits in a Queue or not.
Queue qu = new Queue(); qu.Enqueue(10); qu.Enqueue(20); qu.Enqueue(30); qu.Enqueue("forty"); queue.Contains(22); // true queue.Contains(100); //false
Clear() Method - Queue
The Clear() method removes all the items from a queue.
Example 5: Removes all items from a queue.
Queue qu = new Queue(); qu.Enqueue(10); qu.Enqueue(20); qu.Enqueue(30); qu.Enqueue("forty"); Console.WriteLine("Number of elements in the Queue: {0}", queue.Count); queue.Clear(); Console.WriteLine("Number of elements in the Queue: {0}", queue.Count);
Number of elements in the Queue: 0