The Queue<T>
generic collection is a general-purpose collection that stores objects of the specified type.
A Queue<T>
object represents a First-In, First-Out (FIFO) collection of objects. Objects can be added to the end of the queue and removed from the beginning of the queue.
When to Use a Queue
Use the Queue<T>
generic collection when your application requires:
- A collection of items that must be processed in the order they were added.
- The ability to add items to the end and remove items from the beginning.
Performance Characteristics
The Queue<T>
generic collection is designed for high performance. Most operations (adding and removing elements) are O(1)
.
Example Usage
The following example demonstrates how to declare, initialize, and populate a Queue<string>
, and then process the items.
using System;
using System.Collections.Generic;
public class Example
{
public static void Main()
{
// Declare and initialize a Queue of strings.
Queue<string> queue = new Queue<string>();
// Add elements to the queue.
queue.Enqueue("Apple");
queue.Enqueue("Banana");
queue.Enqueue("Cherry");
// Display the number of elements in the queue.
Console.WriteLine("Count: {0}", queue.Count);
// Dequeue and display elements.
while (queue.Count > 0)
{
string fruit = queue.Dequeue();
Console.WriteLine("Dequeued: {0}", fruit);
}
// Check if the queue is empty.
if (queue.Count == 0)
{
Console.WriteLine("The queue is now empty.");
}
}
}
Methods
The Queue<T>
class provides several useful methods:
Method | Description |
---|---|
Enqueue(T item) | Adds an object to the end of the Queue<T> . |
Dequeue() | Removes and returns the object at the beginning of the Queue<T> . |
Peek() | Returns the object at the beginning of the Queue<T> without removing it. |
Clear() | Removes all objects from the Queue<T> . |
Contains(T item) | Determines whether an element is in the Queue<T> . |
CopyTo(T[] array, int arrayIndex) | Copies the Queue<T> elements to a one-dimensional Array , starting at the specified array index. |
ToArray() | Copies the Queue<T> to a new array. |
Properties
Property | Description |
---|---|
Count | Gets the number of elements contained in the Queue<T> . |