c-sharp
  1. c-sharp-queue

C# Queue

In C#, a Queue is a collection class that represents a first-in, first-out (FIFO) data structure. Elements are added to the end of the queue and removed from the beginning. In this tutorial, we'll discuss how to use Queue in C#.

Syntax

The syntax for creating a new Queue object in C# is as follows:

Queue<T> queue = new Queue<T>();

Here, "T" represents the type of elements that are stored in the Queue.

Example

Let's say we want to create a Queue of integers and add some values to it. Here's how we can implement it:

Queue<int> queue = new Queue<int>();
queue.Enqueue(10);
queue.Enqueue(20);
queue.Enqueue(30);
foreach (int value in queue) {
    Console.WriteLine(value); // Output: 10 20 30
}

Now, we can dequeue the elements from the Queue:

while (queue.Count > 0) {
    int value = queue.Dequeue();
    Console.WriteLine(value); // Output: 10 20 30
}

Output

When we run the example code above, the output will be:

10
20
30
10
20
30

This is because we added three integer values to the Queue, printed them using a foreach loop, and then dequeued the values from the Queue and printed them again.

Explanation

In the example above, we created a Queue of integers, added some values to it using the Enqueue method, and then printed them using a foreach loop. We then dequeued the values from the Queue using the Dequeue method and printed them again using a while loop.

Use

Queues are useful for managing data that needs to be processed in a specific order. They are commonly used in algorithms and other data processing applications.

Important Points

  • You can add elements to the Queue using the Enqueue method.
  • You can remove elements from the Queue using the Dequeue method.
  • The Peek method returns the element at the beginning of the Queue without removing it.
  • The Count property returns the number of elements in the Queue.
  • The Contains method can be used to check if a specific element is in the Queue.

Summary

In this tutorial, we discussed how to use Queue in C#. We covered the syntax, example, output, explanation, use, and important points of Queue in C#. With this knowledge, you can now use Queue in your C# code to manage data that needs to be processed in a specific order.

Published on: