Queue is related to System.Collections.Generic namespace. In, Queue Elements are added to the back (enqueue) and removed from the front (dequeue) of the queue. This is a First-In-First-Out (FIFO) data structure approach.
You need to import the System.Collections.Generic namespace to work with the Queue. To create a Queue, you can use the following code:
You can add elements to the back of the Queue using the Enqueue method:
// inserting integer elements
// inserting string elements
// inserting integer elements
// inserting string elements
You can remove elements from the front of the Queue using the Dequeue method:
// Removes and returns 9
// Removes and returns Apple
// Removes and returns 9
// Removes and returns Apple
You can examine the element at the front of the Queue without removing it using the Peek method:
// Returns 6 (without removing it)
// Returns Mango (without removing it)
// Returns 6 (without removing it)
// Returns Mango (without removing it)
You can check if the Queue is empty using the Count property or the IsEmpty property in C# 7.0 and later:
You can use the foreach loop to iterate through the elements in a Queue. This will process the elements in the order they were added:
// 9, 6, 12, 5, 18, 22 Prints
// Prints Apple,Mango,Cherry,Orange,Grape,Kiwi
// 9, 6, 12, 5, 18, 22 Prints
// Prints Apple,Mango,Cherry,Orange,Grape,Kiwi
You can clear the entire Queue using the Clear method:
// Removes all elements from the queue
// Removes all elements from the queue
// Removes all elements from the queue
// Removes all elements from the queue
Queue is useful when you need to maintain a list of items to be processed in a specific order, where the first item added is the first to be processed.