KeyValuePair
A KeyValuePair
is a Structure
. It has 2 fields of specified types. It stores 2 pieces of data together as a single object.
KeyValuePair
defines a Structure
of any kind of key, and any kind of value. Often we use Strings and Integers for the types, but any type is possible—reference or value.
Here we create a List
that stores KeyValuePairs
. The (Of String
, Integer) syntax is used to specify that the key is a String
, and the value is an Integer.
KeyValuePair
, you must set the key and the value in the constructor.For-Each
. We access Key, and Value.Module Module1 Sub Main() ' Create List of key-value pairs. Dim list As List(Of KeyValuePair(Of String, Integer)) = New List(Of KeyValuePair(Of String, Integer)) list.Add(New KeyValuePair(Of String, Integer)("Cat", 1)) list.Add(New KeyValuePair(Of String, Integer)("Dog", 2)) list.Add(New KeyValuePair(Of String, Integer)("Rabbit", 4)) ' Loop over pairs. For Each pair As KeyValuePair(Of String, Integer) In list ' Display key and value. Console.WriteLine(pair) Next End Sub End Module[Cat, 1] [Dog, 2] [Rabbit, 4]
Sometimes you may want to return 2 values at once from a function. You could use the ByRef
modifier. But the KeyValuePair
can also be returned.
GetPair()
returns a new instance of the KeyValuePair
type that has a specific key and value.Module Module1 Sub Main() Dim pair As KeyValuePair(Of String, String) = GetPair() Console.WriteLine(pair.Key) Console.WriteLine(pair.Value) End Sub Function GetPair() As KeyValuePair(Of String, String) ' Create and return a KeyValuePair instance. Return New KeyValuePair(Of String, String)("image/avif", "avif") End Function End Moduleimage/avif avif
Dictionary
for
-eachThe easiest way to loop over the keys and values in a Dictionary
instance is with the For-Each
loop construct. In this code, we use the KeyValuePair
in the loop.
Module Program Sub Main() ' Create and add values to the Dictionary. Dim animals As Dictionary(Of String, Integer) = New Dictionary(Of String, Integer)() animals("Cat") = 2 animals("Dog") = 1 ' Loop over dictionary. For Each pair As KeyValuePair(Of String, Integer) In animals Console.WriteLine(pair) Next End Sub End Module[Cat, 2] [Dog, 1]
Tuple
The KeyValuePair
is restricted to a key and a value, but the Tuple
type can have more items. If you need 3 fields grouped together, check out the Tuple
type.
Tuple
type is that is must be allocated on the managed heap as an object instance.KeyValuePair
is a structure so it can often be allocated in the stack memory.KeyValuePair
stores a key and a value together in a single object in memory. It is a value type. A common usage is in the For-Each
loop in a Dictionary
.