ContainsKey
This VB.NET Dictionary
function is used to determine whether a key exists within a Dictionary
. It returns True or False based on whether the key exists.
A limitation of ContainsKey
is that it does not return the value. To combine both a key-testing function with a value-getting function, consider TryGetValue
.
To test the result of ContainsKey
on Dictionary
, we must first create a sample Dictionary
. We specify String
keys to mean colors, and Integer values.
ContainsKey
with the argument "tan" which is found in the Dictionary
. ContainsKey
returns True here.Dictionary
, so ContainsKey
returns False.ContainsValue
, which searches the values in the Dictionary
and determines whether the argument is present as a value.Module Module1 Sub Main() Dim colors = New Dictionary(Of String, Integer) colors.Add("tan", 100) colors.Add("lavender", 200) colors.Add("ochre", 300) ' Part 1: look up value that exists with ContainsKey. If colors.ContainsKey("tan") Console.WriteLine("tan was found!") End If ' Part 2: look up missing key. If colors.ContainsKey("blue") ' Not reached. Else Console.WriteLine("blue was not found...") End If ' Part 3: use ContainsValue. If colors.ContainsValue(200) Console.WriteLine("value 200 was found!") End If End Sub End Moduletan was found! blue was not found... value 200 was found!
The Dictionary
in .NET is highly-optimized for key lookup, so ContainsKey
will be fast. But values are not hashed, so they cannot be searched quickly.
ContainsValue
in code that must be fast. Consider creating a separate Dictionary
where the values are keys.Many programs written in VB.NET that use the Dictionary
collection will use ContainsKey
. Sometimes, using TryGetValue
can be better if avoids a second lookup.