Visual Basic .NET - Queue

A Queue is a collection that follows the FIFO (First In First Out) principle, meaning the first item added to the collection will be the first item to be removed. It has two primary operations: Enqueue (adding an item to the end of the queue) and Dequeue (removing an item from the beginning of the queue).

Declaration and Initialization:

 

Dim myQueue As New Queue()

You can also initialize a Queue with values as shown below:

Dim myQueue As New Queue({"apple", "banana", "cherry"})

Adding Items:

To add an item to the end of the queue, use the Enqueue method. The syntax is:

myQueue.Enqueue("newItem")

Removing Items:

To remove an item from the beginning of the queue, use the Dequeue method. The syntax is:

myQueue.Dequeue()

Other Operations:

To get the number of items in the queue, use the Count property. The syntax is:

myQueue.Count

To check if a specific item exists in the queue, use the Contains method. The syntax is:

myQueue.Contains("itemToCheck")

To clear all items from the queue, use the Clear method. The syntax is:

myQueue.Clear()

Example:

Dim myQueue As New Queue({"apple", "banana", "cherry"})
myQueue.Enqueue("date")
myQueue.Enqueue("elderberry")
Console.WriteLine("Count: " & myQueue.Count)
Console.WriteLine("Contains 'banana': " & myQueue.Contains("banana"))
Console.WriteLine("First Item: " & myQueue.Peek())
Console.WriteLine("Removed Item: " & myQueue.Dequeue())