- Queue class is a circular array that stores elements in First In First Out(FIFO) manner, i.e. Element that gets added first into the queue will get removed first from the queue.
- Element gets added from one end and removed from other end.
- Use queue when you want to access element in the same order that it is stored in the collection.
- Use Queue if you want to discard the element as soon as you retrieve it.
See below example of using queue with its main functions.
+
Code
using System; using System.Collections; namespace Queue_Collection_Class { class Program { static void Main(string[] args) { Queue qEmp = new Queue(); Employee emp1 = new Employee() { empId = 111, empName = "Sam" }; Employee emp2 = new Employee() { empId = 112, empName = "Jane" }; Employee emp3 = new Employee() { empId = 113, empName = "Sachin" }; Employee emp4 = new Employee() { empId = 114, empName = "Jack" }; qEmp.Enqueue(emp1); qEmp.Enqueue(emp2); qEmp.Enqueue(emp3); qEmp.Enqueue(emp4); Console.WriteLine("Retrieving elements from Queue\n"); while (qEmp.Count>0) { Console.WriteLine("Employee Id: {0} information", ((Employee)qEmp.Peek()).empId); Employee emp = (Employee)qEmp.Dequeue(); Console.WriteLine("Emplopyee Id : {0} \t Employee Name : {1}", emp.empId,emp.empName); Console.WriteLine("Elements in Queue are:{0}\n",qEmp.Count); } Console.ReadLine(); } } public class Employee { public int empId { get; set; } public string empName { get; set; } } }
In the above code sample, We have created a class called Employee with 2 Properties empId, empName.
We have created a Queue class object qEmp and storing few Employee objects in it. Below are the main functions of Queue that we used in our above code.
Enqueue : Add the element at the end of of Queue.
Dequeue : Retrieve and remove the first element from the Queue.
Peek : Peek function retrieves first element from the Queue but it does not remove it.
Below is the output of above program
No comments :
Post a Comment