How to iterate over a collection of key-value pairs (associative array) in VB.NET

4 Answers

0 votes
' Iterate Over Key–Value Pairs
' Most common pattern

Imports System
Imports System.Collections.Generic

Public Module Program
    Public Sub Main(args As String())

        Dim dict As New Dictionary(Of String, Integer) From {
            {"Alice", 10},
            {"Bob", 17},
            {"Marley", 23},
            {"Charlie", 36}
        }

        For Each kvp In dict
            Console.WriteLine($"Key: {kvp.Key}, Value: {kvp.Value}")
        Next

    End Sub
End Module



' run:
'
' Key: Alice, Value: 10
' Key: Bob, Value: 17
' Key: Marley, Value: 23
' Key: Charlie, Value: 36
'

 



answered Mar 22 by avibootz
0 votes
' Iterate Over Keys Only

Imports System
Imports System.Collections.Generic

Public Class Program
    Public Shared Sub Main(args As String())

        Dim dict As New Dictionary(Of String, Integer) From {
            {"Alice", 10},
            {"Bob", 17},
            {"Marley", 23},
            {"Charlie", 36}
        }

        For Each key In dict.Keys
            Console.WriteLine($"Key: {key}")
        Next

    End Sub
End Class



' run:
'
' Key: Alice
' Key: Bob
' Key: Marley
' Key: Charlie
'




answered Mar 22 by avibootz
0 votes
' Iterate Over Values Only

Imports System
Imports System.Collections.Generic

Public Class Program
    Public Shared Sub Main(args As String())

        Dim dict As New Dictionary(Of String, Integer) From {
            {"Alice", 10},
            {"Bob", 17},
            {"Marley", 23},
            {"Charlie", 36}
        }

        For Each value In dict.Values
            Console.WriteLine($"Value: {value}")
        Next

    End Sub
End Class


' run:
'
' Value: 10
' Value: 17
' Value: 23
' Value: 36
'

 



answered Mar 22 by avibootz
0 votes
' LINQ Options (When Filtering)

Imports System
Imports System.Linq
Imports System.Collections.Generic

Public Class Program
    Public Shared Sub Main(args As String())

        Dim dict As New Dictionary(Of String, Integer) From {
            {"Alice", 10},
            {"Bob", 17},
            {"Marley", 23},
            {"Charlie", 36}
        }

        For Each kvp In dict.Where(Function(pair) pair.Value > 21)
            Dim key = kvp.Key
            Dim value = kvp.Value
            Console.WriteLine($"{key}: {value}")
        Next

    End Sub
End Class


' run:
'
' Marley: 23
' Charlie: 36
'

 



answered Mar 22 by avibootz

Related questions

...