Wednesday 22 August 2018

C#: Queue

Queue is a collection of elements, where elements are processed in FIFO (First In First Out) order.

How to define Queue?
Syntax
Queue queueName = new Queue();

Example
Queue queue = new Queue();

How to add elements to the queue?
By using enqueuer method, you can add elements to queue.

Syntax
queueName. enqueue(element);

Example
queue.enqueue(123);
queue.enqueue(12);

How to remove an element from Queue?
Dequeue() method is used to remove the first element from Queue. It removes and return the object.

Program.cs
using System;
using System.Collections;

namespace collections
{
    class Program
    {

        static void Main(string[] args)
        {
            Queue tasks = new Queue();

            tasks.Enqueue("task1");
            tasks.Enqueue("task2");
            tasks.Enqueue("task3");
            tasks.Enqueue("task4");

            Console.WriteLine("Number Of Elements in Queue are {0}", tasks.Count);
            Console.WriteLine("Last Element of the Stack {0}", tasks.Dequeue());
            Console.WriteLine("Last Element of the Stack {0}", tasks.Dequeue());
            Console.WriteLine("Last Element of the Stack {0}", tasks.Dequeue());
            Console.WriteLine("Last Element of the Stack {0}", tasks.Dequeue());
            Console.WriteLine("Number Of Elements in Queue are {0}", tasks.Count);

        }
    }
}

Output
Number Of Elements in Queue are 4
Last Element of the Stack task1
Last Element of the Stack task2
Last Element of the Stack task3
Last Element of the Stack task4
Number Of Elements in Queue are 0




Previous                                                 Next                                                 Home

No comments:

Post a Comment