C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Note: When creating a KeyValuePair, you must set the key and the value in the constructor.
Finally: We loop through all the elements of the list with For-Each. We access Key, and Value.
For Each, ForVB.NET program that creates List of KeyValuePair instances
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)("dot", 1))
list.Add(New KeyValuePair(Of String, Integer)("net", 2))
list.Add(New KeyValuePair(Of String, Integer)("Codex", 3))
' Loop over pairs.
For Each pair As KeyValuePair(Of String, Integer) In list
' Get key.
Dim key As String = pair.Key
' Get value.
Dim value As Integer = pair.Value
' Display.
Console.WriteLine("{0}, {1}", key, value)
Next
End Sub
End Module
Output
dot, 1
net, 2
Codex, 3
Here: In this example, the GetPair Function returns a new instance of the KeyValuePair type that has a specific key and value.
VB.NET program that returns KeyValuePair from Function
Module Module1
Sub Main()
Dim pair As KeyValuePair(Of Integer, Integer) = GetPair()
Console.WriteLine(pair.Key)
Console.WriteLine(pair.Value)
End Sub
Function GetPair() As KeyValuePair(Of Integer, Integer)
' Create new pair.
Dim pair As KeyValuePair(Of Integer, Integer) =
New KeyValuePair(Of Integer, Integer)(5, 8)
' Return the pair.
Return pair
End Function
End Module
Output
5
8
Note: One drawback of the Tuple type is that is must be allocated on the managed heap as an object instance.
However: The KeyValuePair is a structure so it can often be allocated in the stack memory.
Tuple