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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
using System; using System.Collections.Generic; namespace Stack_and_Queues_2 { class Program { static void Main(string[] args) { //defining a queue of integers Queue<int> queue = new Queue<int>(); } } } |
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
1 2 3 |
//adding element to a queue queue.Enqueue(1); |
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
1 2 3 |
//printing the element at the front of the queue Console.WriteLine("The value at the front of the queue is : {0}", queue.Peek()); |
Let’s add few values to our queues like this
1 2 3 4 5 6 7 8 9 |
//adding elements to the queue and printing the element at the front queue.Enqueue(1); Console.WriteLine("The value at the front of the queue is : {0}", queue.Peek()); queue.Enqueue(2); Console.WriteLine("Top value in the queue is : {0}", queue.Peek()); queue.Enqueue(3); Console.WriteLine("Top value in the queue is : {0}", queue.Peek()); |
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
1 2 3 4 5 6 7 8 |
//as long as the count is > 0, as long as the queue is not empty while (queue.Count > 0) { //Dequeue() will return the element that was removed from the queue Console.WriteLine("The front value {0} was removed from the queue", queue.Dequeue()); //print the queue count Console.WriteLine("Current queue count is : {0}", queue.Count); } |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
//a class named order we will use it to store instances of it inside a queue because class Order { //order ID public int OrderId { get; set; } //quantity of the order public int OrderQuantity { get; set; } //simple constructor public Order(int id,int orderQuanttity) { this.OrderId = id; this.OrderQuantity = orderQuanttity; } //print message on the screen that the order was processed public void ProcessOrder() { //print the message Console.WriteLine($"Order {OrderId} processed!."); } } |
In the main method, we defined 2 methods
- RecieveOrdersFromBranch1
- 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
//this method will create an array of orders an return it static Order[] RecieveOrdersFromBranch1() { //creating new orders array Order[] orders = new Order[] { new Order(1,5), new Order(2,4), new Order(6,10) }; return orders; } //this method will create an array of orders an return it static Order[] RecieveOrdersFromBranch2() { //creating new orders array and initializing it with some objects of type Order Order[] orders = new Order[] { new Order(3,5), new Order(4,4), new Order(5,10) }; // return the array of orders that we created return orders; } |
In the main method, we defined a queue called ordersQueue
1 2 3 |
//create a new queue for our orders Queue<Order> ordersQueue = new Queue<Order>(); |
Then using a for each loop we will Enqueue the orders we got from the methods we defined above
1 2 3 4 5 6 7 8 9 10 11 12 13 |
//RecieveOrdersFromBranch1() method will return an array of orders //this for each will go through each Order in the array returned by the method foreach(Order o in RecieveOrdersFromBranch1()) { //add each order to the queue ordersQueue.Enqueue(o); } //RecieveOrdersFromBranch1() method will return an array of orders //this for each will go through each Order in the array returned by the method foreach(Order o in RecieveOrdersFromBranch2()) { //add each order to the queue ordersQueue.Enqueue(o); } |
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
1 2 3 4 5 6 7 8 9 |
//as long as the queue is not empty while (ordersQueue.Count > 0) { //remove the order At the front of the queue //and store it in a variable called currentOrder Order currentOrder = ordersQueue.Dequeue(); //process the order currentOrder.ProcessOrder(); } |
Complete Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 |
using System; using System.Collections.Generic; namespace Stack_and_Queues_2 { class Program { static void Main(string[] args) { //defining a queue of integers Queue<int> queue = new Queue<int>(); //adding elements to the queue and printing the element at the front queue.Enqueue(1); Console.WriteLine("The value at the front of the queue is : {0}", queue.Peek()); queue.Enqueue(2); Console.WriteLine("Top value in the queue is : {0}", queue.Peek()); queue.Enqueue(3); Console.WriteLine("Top value in the queue is : {0}", queue.Peek()); //as long as the count is > 0, as long as the queue is not empty while (queue.Count > 0) { //Dequeue() will return the element that was removed from the queue Console.WriteLine("The front value {0} was removed from the queue", queue.Dequeue()); //print the queue count Console.WriteLine("Current queue count is : {0}", queue.Count); } //create a new queue for our orders Queue<Order> ordersQueue = new Queue<Order>(); //RecieveOrdersFromBranch1() method will return an array of orders //this for each will go through each Order in the array returned by the method foreach(Order o in RecieveOrdersFromBranch1()) { //add each order to the queue ordersQueue.Enqueue(o); } //RecieveOrdersFromBranch1() method will return an array of orders //this for each will go through each Order in the array returned by the method foreach(Order o in RecieveOrdersFromBranch2()) { //add each order to the queue ordersQueue.Enqueue(o); } //as long as the queue is not empty while (ordersQueue.Count > 0) { //remove the order At the front of the queue //and store it in a variable called currentOrder Order currentOrder = ordersQueue.Dequeue(); //process the order currentOrder.ProcessOrder(); } } ///this method will create an array of orders an return it static Order[] RecieveOrdersFromBranch1() { //creating new orders array Order[] orders = new Order[] { new Order(1,5), new Order(2,4), new Order(6,10) }; return orders; } //this method will create an array of orders an return it static Order[] RecieveOrdersFromBranch2() { //creating new orders array and initializing it with some objects of type Order Order[] orders = new Order[] { new Order(3,5), new Order(4,4), new Order(5,10) }; // return the array of orders that we created return orders; } } //a class named order we will use it to store instances of it inside a queue because class Order { //order ID public int OrderId { get; set; } //quantity of the order public int OrderQuantity { get; set; } //simple constructor public Order(int id,int orderQuanttity) { this.OrderId = id; this.OrderQuantity = orderQuanttity; } //print message on the screen that the order was processed public void ProcessOrder() { //print the message Console.WriteLine($"Order {OrderId} processed!."); } } } |
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.