1

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
Andreas
  • 5,393
  • 9
  • 44
  • 53
K_McCormic
  • 334
  • 2
  • 5
  • 17
  • Assuming you actually create chardict somewhere and have option-strict disabled to allow string->char (would string not be a better choice?) that should work, you need to expand your example – Alex K. Feb 22 '12 at 10:43

3 Answers3

1

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

Nikhil Saswade
  • 167
  • 2
  • 6
  • 16
0

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.

-1

Your syntax seems correct

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

what error you are getting?

Anil D
  • 1,989
  • 6
  • 29
  • 60
  • oh i wanted it to display the value that corresponds to the letter A. in this case display the character 0 – K_McCormic Feb 22 '12 at 10:46
  • 1
    Inside If loop, add, Dim num As Integer = dictionary.Item("A") Console.WriteLine(num) – Anil D Feb 22 '12 at 10:53
  • i'm getting an error 'nullreferenceexception was unhandled' object reference not set to an instance of an object (this is referring to the dictionary 'chardict.Add("A", 0) – K_McCormic Feb 22 '12 at 11:09
  • You have set dictionary to nothing, need to remove "Nothing" From Dim chardict As Dictionary(Of Char, Integer), Need to use New keyword, keep it just, Dim chardict As New Dictionary(Of Char, Integer) – Anil D Feb 22 '12 at 11:12
  • 2
    What does "Do" mean in this case? – tmighty Mar 24 '14 at 00:01