K_McCormic
K_McCormic

Reputation: 334

How to find values in dictionary in VB

I have this dictionary:

Dim chardict As Dictionary(Of Char, Integer) = Nothing
chardict.Add("A", 0)
chardict.Add("B", 1)

I want to do the following if statement but I am a bit stuck on the syntax:

if chardict.containskey("A")
    'display the value that corrosponds to the letter "A"
    'in this case display the character 0
    [some code]
end if

Upvotes: 1

Views: 12055

Answers (3)

XboxMeister
XboxMeister

Reputation: 1

Actually I'm pretty sure this code will throw an exception because the key wasn't found in the dictionary. "Single" is the value, not the key in this situation so indexing against a value that isn't a valid key will throw a key not found exception.

I actually need that ability (for some reason the API I'm using has a dictionary where the value I need to get is the key and the only way to look it up is by the friendly name they've associated to the key). Maybe there's a better way but my kludgy solution was to loop thru all the dictionary entries and and find the value I needed and then grab the key associated with it. So far I haven't found a way to look up the key by providing the value other than the loop or using Find() on the list but maybe I'm just missing something.

Upvotes: 0

Nikhil Saswade
Nikhil Saswade

Reputation: 177

Just pass value to dictionary and it will return you a Key means if you dictionary is as follows:

Private Status As New Dictionary (Of String, String)
Status.Add("Y", "Married")
Status.Add("N", "Single")
Status.Add("X", "Its Complicated")

Below line of code will return you key

Dim Key As String = Status("Single")

Key = N

Upvotes: 1

Anil D
Anil D

Reputation: 2009

Your syntax seems correct

If dictionary.ContainsKey("A") Then
    Do
End If

what error you are getting?

Upvotes: -1

Related Questions