Queue with Examples in C#?


The Queue class in C# is the first-in, first-out collection of objects. Let us see some of the methods of the Queue class in C# −

Sr.NoMethods & Description
1Clear()
Removes all objects from the Queue<T>.
2Contains(T)
Determines whether an element is in the Queue<T>.
3CopyTo(T[], Int32)
Copies the Queue>T< elements to an existing onedimensional Array, starting at the specified array index.
4Dequeue()
Removes and returns the object at the beginning of the Queue<T>.
5Enqueue(T)
Adds an object to the end of the Queue<T>.
6Equals(Object)
Determines whether the specified object is equal to the current object.(Inherited from Object)
7GetEnumerator()
Returns an enumerator that iterates through the Queue<T>
8GetHashCode()
Serves as the default hash function. (Inherited from Object)
9GetType()
Gets the Type of the current instance.

Example

Let us now see some examples −

To get the object at the beginning of the Queue, the code is as follows −

 Live Demo

using System;
using System.Collections.Generic;
public class Demo {
   public static void Main() {
      Queue<string> queue = new Queue<string>();
      queue.Enqueue("A");
      queue.Enqueue("B");
      queue.Enqueue("C");
      queue.Enqueue("D");
      queue.Enqueue("E");
      queue.Enqueue("F");
      queue.Enqueue("G");
      Console.WriteLine("Count of elements = "+queue.Count);
      Console.WriteLine("Element at the beginning of queue = " + queue.Peek());
   }
}

Output

This will produce the following output −

Count of elements = 7
Element at the beginning of queue = A

To remove all objects from the Queue, the code is as follows −

Example

 Live Demo

using System;
using System.Collections.Generic;
public class Demo {
   public static void Main() {
      Queue<string> queue = new Queue<string>();
      queue.Enqueue("Gary");
      queue.Enqueue("Jack");
      queue.Enqueue("Ryan");
      queue.Enqueue("Kevin");
      queue.Enqueue("Mark");
      queue.Enqueue("Jack");
      queue.Enqueue("Ryan");
      queue.Enqueue("Kevin");
      Console.Write("Count of elements = ");
      Console.WriteLine(queue.Count);
      queue.Clear();
      Console.Write("Count of elements (updated) = ");
      Console.WriteLine(queue.Count);
   }
}

Output

This will produce the following output −

Count of elements = 8
Count of elements (updated) = 0

Updated on: 16-Dec-2019

112 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements