Introduction

In this lesson, we will see how to implement a Queue in our application

As we discussed, Queues are significant and used a lot by our operating system to handle task scheduling and many other processes.

Queues should be used when the order of the data is important as we will see in our example later

1 Defining a Queue

As with any other Collection, a queue can be defined and initialized like a normal collection

2 Adding and Viewing Data in a Queue

To add data to our queue we use the method Enqueue(), it adds elements to the back (Rear) of the queue

Like a stack, we can view the element at the front of the queue using the Peek() method.

it will return the element at the front of the queue without removing it

Let’s add few values to our queues like this

3 Removing Data from a queue

Using the Dequeue() method we can remove elements from the front of the queue thus pushing the next element to the front

We can also use the Count property to check the number of elements in our queue since it’s a collection

Example

In E-Commerce platforms, the seller will receive orders, and these orders should be processed so that the service time/waiting time per customer should be minimum. That’s why using a queue is very practical since we care about the order of data that we received

Let’s consider the following simple class called Order with two properties :

1.OrderId

2.OrderQuantity

We also have a method called ProcessOrder()

which will print a message indicating that the order was processed

In the main method, we defined 2 methods

  1. RecieveOrdersFromBranch1
  2. RecieveOrdersFromBranch2

which will return an array of orders received from different branches

In a real scenario, these orders would be received from a database for example

In the main method, we defined a queue called ordersQueue

Then using a for each loop we will Enqueue the orders we got from the methods we defined above

To process our orders we will go through our queue one by one then we will remove this element from our queue and process it until our queue is empty and all orders are finally processed

Complete Code