Queue
It represent a FIFO (First In First Out) collection of object. Queue is used when you need first-in, first-out access of object that means accessing the first inserting item. Queue basically consist of two operation Enqueue and Dequeue. When you insert an element in Queue , it is called Enqueue, and when you extract the item from Queue , it is called Dequeue. Enqueue operation is perform at the end of queue and Dequeue operation take place at front of the queue. To use Queue data type in c# first you should need to use System.Collections namespace.
Properties of Queue
-
Count return the number of elements present in the Queue.
Method of Queue:
- public virtual void Enqueue(object obj); It simply insert an object at the end of queue.
- public virtual object Dequeue(object obj); It simply remove and return the object from front of the queue.
-
public virtual void Clear(); It clears the queue means this method remove all the element from queue.
-
public virtual object Peek(); This method return the object from front of the queue (without Removing).
-
public virtual object[] ToArray(); This method copy the queue into a object array.
-
public virtual bool Contains(object obj); This method is used to check whether an element is exist in the queue. It return True when item exist in the queue otherwise it return False.
-
public virtual void TrimToSize(); This method sets the capacity to the actual number of elements present in the Queue. Basically the capacity is not increased one by one. Capacity is just doubled each time whenever the size reaches the threshold. So TrimToSize() method sets the capacity to exact the size of queue.
Here is the example:
- using System;
- using System.Collections;
- namespace Teq_Cdac
- {
- class Program
- {
- static void Main(string[] args)
- {
- Queue q = new Queue();
- q.Enqueue("Pankaj");
- q.Enqueue(1);
- q.Enqueue(10.5);
- q.Enqueue(true);
- q.Enqueue('A');
- Console.WriteLine("Count : {0}", q.Count);
- Console.WriteLine();
- Console.WriteLine("Element in Queue : ");
- foreach(object obj in q)
- Console.WriteLine(obj);
- Console.WriteLine();
- Console.WriteLine("End element of Queue : {0}", q.Peek());
- Console.WriteLine();
- object TopElement = q.Dequeue();
- Console.WriteLine("Removing End element of Queue = {0}\nNow End element of Queue = {1}\n", TopElement, q.Peek());
- if (q.Contains("Pankaj")) Console.WriteLine("Pankaj Found");
- else Console.WriteLine("Pankaj Not found");
- Object[] ob = q.ToArray();
- Console.WriteLine();
- foreach(object obj in ob)
- Console.WriteLine(obj);
- q.TrimToSize();
- q.Clear();
- Console.WriteLine();
- Console.WriteLine("Count : {0}", q.Count);
- Console.ReadKey();
- }
- }
- }
Output