Skip to content

C# Queues

c# queues
Become a developer with our complete learning paths
Become a developer with our complete learning paths

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.

Lost in coding? Discover our Learning Paths!
Lost in coding? Discover our Learning Paths!
Tags:
Become a senior C# developer and build software like an A-Player
Join the C# Progress Academy and master C# .NET, ASP.NET, Design Patterns, Asynchronous Development, Clean Code, and much more.
Become a senior C# developer and build software like an A-Player
Join the C# Progress Academy and master C# .NET, ASP.NET, Design Patterns, Asynchronous Development, Clean Code, and much more.