Zach Johnson Zach Johnson - 1 month ago 8
Vb.net Question

How can I dequeue an item at certain index in a queue of string?

I am trying to dequeue items if they contain a certain string. This is the idea I was hoping would work but does not:

Dim baseUri As String = myuri.GetLeftPart(UriPartial.Authority)
For i = workerURLs.Count - 1 To 0 Step -1
If workerURLs(i).Contains(baseUri) Then
workerURLs.Dequeue(i)
End If
Next


Since the queue method has no "Dequeue at index" option like a list would how can I accomplish this?

Uno Uno
Answer

One way to implement it would be to wrap a Queue(Of T) and recreate it when an element gets "dequeued" from the middle:

Class IndexableQueue(Of T)

    Private _queue As New Queue(Of T)()

    Public Sub Enqueue(item As T)
        _queue.Enqueue(item)
    End Sub

    Public Function Dequeue() As T
        Return _queue.Dequeue()
    End Function

    Public Function Dequeue(index As Integer) As T
        Dim list = _queue.ToList()

        Dim item = list(index)

        list.RemoveAt(index)

        _queue = New Queue(Of T)(list)

        Return item
    End Function

End Class

This is the simplest implementation although it's not the most efficient as we are recreating the Queue on every call to Dequeue(Integer). But if it's uncommon and the queue is not massive it should be fine.

The best way would be to completely reimplement the Queue and use a List instead of an array as underlying type.