Queue in Visual Basic .NET

Last Updated: March 19, 2020

Queue is a generic collection in VB.NET
Queue implements the FIFO algorithm. Element added first is removed first
Enqueue() is used to add element to Queue. Look at the following piece of code how we can add element to Queue and how we can iterate the Queue

Module Module1

    Sub Main()
        Dim q As New Queue
        q.Enqueue("Sunday")
        q.Enqueue("Monday")
        q.Enqueue("Tuesday")
        q.Enqueue("Wednesday")
        q.Enqueue("Thursday")
        q.Enqueue("Friday")
        q.Enqueue("Saturday")
        ' Loop over the Queue.
        For Each element As String In q
            Console.WriteLine(element)
        Next


    End Sub

End Module

Output

Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday

Now I will run Dequeqe() to remove element from Queue

Module Module1

    Sub Main()
        Dim q As New Queue
        q.Enqueue("Sunday")
        q.Enqueue("Monday")
        q.Enqueue("Tuesday")
        q.Enqueue("Wednesday")
        q.Enqueue("Thursday")
        q.Enqueue("Friday")
        q.Enqueue("Saturday")
        ' Loop over the Queue.
        For Each element As String In q
            Console.WriteLine(element)
        Next

        q.Dequeue()
        Console.WriteLine("-----------------")
        Console.WriteLine("After Dequeue")
        For Each element As String In q
            Console.WriteLine(element)
        Next

    End Sub

End Module

When you look at the output you can observe that first added element “Sunday” is removed first

Output
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
-----------------
After Dequeue
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday

You can use CopyTo() to copy the Queue to array

Module Module1

    Sub Main()
        Dim q As New Queue
        q.Enqueue("Sunday")
        q.Enqueue("Monday")
        q.Enqueue("Tuesday")
        q.Enqueue("Wednesday")
        q.Enqueue("Thursday")
        q.Enqueue("Friday")
        q.Enqueue("Saturday")

        Dim arr(q.Count() - 1) As String
        q.CopyTo(arr, 0)
        For Each elemnt In arr
            Console.WriteLine(elemnt)
        Next

        Console.ReadLine()
    End Sub

End Module