rkz
rkz

Reputation: 13

VB.net collection

Class MainWindow

    Dim states As Collection = New Collection()

    Sub Output(Value As String)

        txtOutput.Text += Value + vbCrLf

    End Sub

    Sub ClearOutput(sender As Object, e As RoutedEventArgs) Handles btnClear.Click
        txtOutput.Text = ""
        txtInput.Text = ""
    End Sub

    Sub btnAdd_Click(sender As Object, e As RoutedEventArgs) Handles btnAdd.Click

        Dim input As String = txtInput.Text
        'Dim state As String = input.Substring(0, input.IndexOf(",")).ToString
        'Dim stateID As String = input.Substring(input.IndexOf(" ")).ToString

        states.Add(input)
        Output("You added: " + input)

    End Sub

    Sub btnGet_Click(sender As Object, e As RoutedEventArgs) Handles btnGet.Click

        Dim stateID As String = txtInput.Text.ToString
        If states.Contains(stateID) Then
            Output("You requested: " + states.Item(stateID))
        Else
            Output("Not found")
        End If
    End Sub

    Sub btnRemove_Click(sender As Object, e As RoutedEventArgs) Handles btnRemove.Click

        Dim stateID As String = txtInput.Text.ToString
        If states.Contains(stateID) Then
            states.Remove(stateID)
            txtOutput.Text = ""
            Output(stateID + " removed; here's what's left:")
            OutputStates()
        Else
            Output("Not found")
        End If

    End Sub

    Sub btnShow_Click(sender As Object, e As RoutedEventArgs) Handles btnShow.Click
        OutputStates()
    End Sub

    Sub OutputStates()
        For Each state As String In states
            Output(state)
        Next
    End Sub
End Class

I'm done with the Add and Show button. the input is: California, CA

But my problem is the remove and get button. For example i inputted "CA" as a stateID, if i click the get or remove button, it will check if states collection has an item with the "CA" string, but the answer is always not found even if i use states(1).Contains(stateID) which is California, CA

Upvotes: 0

Views: 78

Answers (1)

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112324

In .NET you would be using a HashSet(Of T).

Dim states As HashSet(Of String) = New HashSet(Of String)()

states.Add(stateID)

If states.Contains(stateID) Then ...

Note that the HashSet is case sensitive by default. If you want it to be case-insensitive, initialize it like this:

Dim states As HashSet(Of String) = New HashSet(Of String)(StringComparer.OrdinalIgnoreCase)

Note also that (with Collection) states(1) returns a stateID. Therefore you could compare

states(1) = stateID 'Should return True if 1st state is "CA" and stateID is "CA"

states(1).Contains(stateID) makes no sense. Probably here Contains refers to the characters contained in state(1).

Upvotes: 1

Related Questions