Skip to content

C# Queues

  • CSharp
c# queues

Introduction

In this lesson, you will learn everything you need to know about C# queues.

Queues are significant and used a lot by our operating system to handle task scheduling and many other processes. They should be used when the order of the data is important as we will see in our example later.

1. Defining queues in C#

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(), which 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 C# queues

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 of C# queues

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

If you want to continue learning you might want to read out our article on Lambda Expression in C# or if you want to land your first job as a developer, you want to check out our C# Progress Academy.

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *

Enter your email and we will send you the PDF guide:
Enter your email and we will send you the PDF guide