How is the queue used in C#?
In C#, the Queue is a first-in, first-out (FIFO) data structure. It can be seen as a container where elements can only be added at one end (called the “tail”) and removed at the other end (called the “head”). Queues can be used for operations that need to be performed in a specific order.
Below are some commonly used methods and usage of Queue.
- Enqueue: Adding elements to the end of the queue.
Queue<int> queue = new Queue<int>();
queue.Enqueue(1);
queue.Enqueue(2);
queue.Enqueue(3);
- Dequeue: Remove and return the head element of the queue.
int element = queue.Dequeue();
- Peek: Retrieve the first element of the queue without removing it.
int element = queue.Peek();
- Count: Return the number of elements in the queue.
int count = queue.Count;
- Check if the queue contains the specified element.
bool contains = queue.Contains(2);
- Clear: Remove all elements from the queue.
queue.Clear();
- Iterate through the elements in the queue using a foreach loop.
foreach (int element in queue)
{
Console.WriteLine(element);
}
Please note that Queue is a thread-safe data structure that can be used in a multi-threaded environment. If you require a thread-safe queue, you can use the ConcurrentQueue class.