Data Structures

C# Queues

Working with Queues

C# queues use Queue<T> for FIFO data structures.

Introduction to C# Queues

A queue is a collection designed to hold elements prior to processing. The Queue class in C# is a generic collection that provides functionality for a first-in, first-out (FIFO) data structure. This means that the first element added to the queue will be the first one to be removed. Queues are useful when you need to manage tasks in the order they were received.

Creating a Queue in C#

To create a queue in C#, you need to use the Queue<T> class from the System.Collections.Generic namespace. Here's a simple example of how to create and initialize a queue:

Basic Operations with Queues

Queues support several basic operations, including adding items, removing items, and inspecting the next item. Let's explore these operations:

Enqueuing Elements

The Enqueue method is used to add elements to the end of the queue. Here’s how you can add more elements:

Dequeuing Elements

The Dequeue method is used to remove and return the element at the front of the queue. This operation throws an InvalidOperationException if the queue is empty:

Peeking at the Front Element

To view the element at the front of the queue without removing it, you can use the Peek method. This is useful when you need to see the next item to be processed:

Checking the Queue's Count

You can check the number of elements in the queue using the Count property. This is helpful to determine how many items are still in the queue:

Iterating Through a Queue

Although queues are designed for FIFO operations, you can still iterate through them without modifying the queue. Here's an example of how to do this:

When to Use Queues

Queues are ideal for scenarios where you need to process elements in the exact order they arrive. Common use cases include task scheduling, breadth-first search algorithms, and handling requests in a multi-threaded environment.

Previous
HashSets
Next
Tasks