Queue Interface In C#

CsharpProgrammingServer Side Programming

Queue represents a first-in, first out collection of object. It is used when you need a first-in, first-out access to items. When you add an item to the list, it is called enqueue, and when you remove an item, it is called deque.

Let us see an example of the Queue class.

To add elements, use Enqueue −

Queue q = new Queue();

q.Enqueue('X');
q.Enqueue('Y');
q.Enqueue('Z');

To delete elements, use Dequeue −

// remove elements
while (q.Count > 0)
Console.WriteLine(q.Dequeue());

Let us see an example to add elements in a queue.

Example

 Live Demo

using System;
using System.Collections;

namespace Demo {
   class Program {
      static void Main(string[] args) {
         Queue q = new Queue();

         q.Enqueue('t');
         q.Enqueue('u');
         q.Enqueue('v');
         q.Enqueue('w');
         q.Enqueue('x');

         Console.WriteLine("Current queue: ");
         foreach (char c in q) Console.Write(c + " ");

         Console.WriteLine();
         Console.ReadKey();
      }
   }
}

Output

Current queue:
t u v w x


raja
Published on 20-Aug-2018 12:42:42
Advertisements