What is the Queue class in C#?

CsharpProgrammingServer Side Programming

To represent a first-in first-out collection of objects in C#, use the Queue class. When you add an item in the list, it is called enqueue, and when you remove an item, it is called deque.

Some of the methods of the Queue class include.

Sr.NoMethod & Description
1public virtual void Clear();
Removes all elements from the Queue.
2public virtual bool Contains(object obj);
Determines whether an element is in the Queue.
3public virtual object Dequeue();
Removes and returns the object at the beginning of the Queue.
4public virtual void Enqueue(object obj);
Adds an object to the end of the Queue.
5public virtual object[] ToArray();
Copies the Queue to a new array.

Let us see how to work with enqueue and deque in C# that comes under the queue class.

Example

 Live Demo

using System;
using System.Collections;
namespace Demo {
   class Program {
      static void Main(string[] args) {
         Queue q = new Queue();
         q.Enqueue('A');
         q.Enqueue('B');
         q.Enqueue('C');
         q.Enqueue('D');
         Console.WriteLine("Current queue: ");
         foreach (char c in q) Console.Write(c + " ");
         Console.WriteLine();
         q.Enqueue('E');
         q.Enqueue('F');
         q.Enqueue('G');
         q.Enqueue('H');
         Console.WriteLine("Current queue: ");
         foreach (char c in q) Console.Write(c + " ");
         Console.WriteLine();
         Console.WriteLine("Removing some values ");
         char ch = (char)q.Dequeue();
         Console.WriteLine("Value removed: {0}", ch);
         ch = (char)q.Dequeue();
         Console.WriteLine("Value removed: {0}", ch);
         Console.ReadKey();
      }
   }
}

Output

Current queue:
A B C D
Current queue:
A B C D E F G H
Removing some values
Value removed: A
Value removed: B

Above, using enqueue the elements are added.

Queue q = new Queue();
q.Enqueue('A');
q.Enqueue('B');
q.Enqueue('C');
q.Enqueue('D');

The elements are deleted using dequeue.

char ch = (char)q.Dequeue();
Console.WriteLine("Value removed: {0}", ch);
raja
Published on 18-Sep-2018 07:39:57
Advertisements