Curriculum
In C#, a Queue is a collection that represents a first-in, first-out (FIFO) queue of objects. Elements can be enqueued (added to the end of the queue) and dequeued (removed from the front of the queue). Here’s an example of using a Queue to store and manipulate a collection of integers:
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
// Create a queue of integers
Queue<int> numbers = new Queue<int>();
// Enqueue some numbers onto the queue
numbers.Enqueue(1);
numbers.Enqueue(2);
numbers.Enqueue(3);
// Display the front number in the queue
Console.WriteLine("Front number in the queue: {0}", numbers.Peek());
// Dequeue a number from the queue and display it
int dequeuedNumber = numbers.Dequeue();
Console.WriteLine("Dequeued number: {0}", dequeuedNumber);
// Display the remaining numbers in the queue
Console.WriteLine("Remaining numbers in the queue:");
foreach (int number in numbers)
{
Console.WriteLine(number);
}
}
}
In this example, we first create an empty Queue<int> object called numbers. We then use the Enqueue method to add some numbers to the end of the queue. We use the Peek method to display the front number in the queue without removing it. We use the Dequeue method to remove and return the front number in the queue, which we store in the dequeuedNumber variable. Finally, we use a foreach loop to display the remaining numbers in the queue.
Here are some other useful methods provided by the Queue class:
Count: Returns the number of elements in the queue.Contains: Determines whether an element is in the queue.Clear: Removes all elements from the queue.ToArray: Copies the elements of the queue to a new array.Here’s an example that demonstrates some of these methods:
// Create a queue of strings
Queue<string> names = new Queue<string>();
// Enqueue some names onto the queue
names.Enqueue("Alice");
names.Enqueue("Bob");
names.Enqueue("Charlie");
// Check if the queue contains a certain name
if (names.Contains("Bob"))
{
Console.WriteLine("Queue contains the name Bob");
}
// Create an array from the queue and display it
string[] nameArray = names.ToArray();
Console.WriteLine("Array from queue: [{0}]", string.Join(", ", nameArray));
// Clear the queue
names.Clear();
// Display the number of elements in the queue (which should be 0)
Console.WriteLine("Number of elements in queue: {0}", names.Count);
It’s important to note that Queue provides many other useful properties and methods for working with queues, such as TrimExcess to optimize the internal array to the actual number of elements, GetEnumerator to get an enumerator that iterates through the queue, and CopyTo to copy the elements of the queue to an existing array.