C# Queue

C# Queue, is a first-in, first-out data structure, with methods to add an item to one end of the queue, remove an item from the other end, and examine an item without removing it. It is based on First-In First out (FIFO) System. Its mean, me can store Objects in a Queue from one end and can remove from other end.

In Queue, using Enqueue() and Dequeue() methods, we can add or delete an element from the queue. Here, the Enqueue() method is useful to add elements at the end of the queue and the Dequeue() method is useful to remove elements start from the queue.

Declaring Queue in C#

We can declare queue in C# as follows

Queue myQueue= new Queue();

We can perform following functions on Queue:

  • Enqueue: Add an Item in Queue, at the end of the queue
    myQueue.Enqueue(1);
    myQueue.Enqueue(2);
    myQueue.Enqueue(3);?
  • Dequeue: Remove the oldest item from the start of the queue
    myQueue.Dequeue();?
  • Peek: Returns the object at the beginning of the Queue without removing it.
    myQueue.Peek();?
  • Clear: Removes all objects from the Queue.
  • Contains: It is used to determine whether an element exists in a queue or not.

queue-c-sharp-min.png

Let's take a look at an complete example of C# queue

using System;
using System.Collections;
					
public class QueueProgramInCsharp
{
	public static void Main()
	{
		Queue myQueue= new Queue();
		
		//add elements in queue
		myQueue.Enqueue(1);
		myQueue.Enqueue(2);
		myQueue.Enqueue(3);
		
		//print queue
		Console.WriteLine("Queue after adding elements:");
		PrintQueue(myQueue);
		Console.WriteLine();
		
		//remove element from queue
		myQueue.Dequeue();
		Console.WriteLine();
		
		//check queue now
		Console.WriteLine("Queue after removing a element:");
		PrintQueue(myQueue);
		Console.WriteLine();
		
		//using peek method to get top item of queue
		Console.WriteLine("Top item of queue using peek:"+ myQueue.Peek());
	   	Console.WriteLine();
		
		//check if element exists in queue
		Console.WriteLine("Element  3 exists in queue :"+ myQueue.Contains(3));
	   	Console.WriteLine();
		
		//clear queue
		myQueue.Clear();
		Console.WriteLine("After using clear method, try to print queue items, no items exists and hence nothing is printed");
		PrintQueue(myQueue);
	}
	
	//print queue
	public static void PrintQueue(Queue myQueue)
	{
		foreach(var item in myQueue)
		{
			Console.WriteLine(item);
		}
	}
}

Output:

Queue after adding elements:
1
2
3


Queue after removing a element:
2
3

Top item of queue using peek:2

Element  3 exists in queue :True

After using clear method, try to print queue items, no items exists and hence nothing is printed

In the above program, we have used all the important functions used in Queue like Enqueue, Dequeue, Peek, Contains and clear. I have also used foreach lopp to print queue elements one by one.


Share Tweet