Home > front end >  How to use a look up in a hashtable vb.net
How to use a look up in a hashtable vb.net

Time:01-09

EDIT I have created a Hash table and I want to do a lookup and extract the Name value where ID is = line.substring(4,2).

ID Name

01 John

02 Bob

03 Joe

04 Mary

I have the following code:

    Sub Main()
    ' Create Hashtable instance.
    Dim table As Hashtable = New Hashtable

    table.Add("01", "John")
    table.Add("02", "Bob")
    table.Add("03", "Joe")
    table.Add("04", "Mary")

    '-lookup and extract the Name value where ID is = line.substring(4,2)

End Sub

CodePudding user response:

Agreed, use a Generic Dictionary(Of String, String).

...but, here's how to do what you asked:

Dim table As Hashtable = New Hashtable

table.Add("01", "John")
table.Add("02", "Bob")
table.Add("03", "Joe")
table.Add("04", "Mary")

Dim line As String = "abcd02efg"
Dim ID As String = line.Substring(4, 2)
If table.ContainsKey(ID) Then
    Dim value As String = table(ID)
    MessageBox.Show(ID & " = " & value)
Else
    MessageBox.Show("Key not found! ID = " & ID)
End If
  • Related