How to combine 2 dictionaries into a third dictionary in VB.NET

3 Answers

0 votes
Imports System
Imports System.Collections.Generic

Class Program
    Public Shared Sub Main()
        Dim dict1 = New Dictionary(Of Integer, String) From {
            {1, "aaa"},
            {2, "bbb"}
        }
        Dim dict2 = New Dictionary(Of Integer, String) From {
            {3, "ccc"},
            {4, "ddd"},
            {2, "XYZ"}
        }
        Dim combined = New Dictionary(Of Integer, String)(dict1)

        For Each kvp In dict2
            combined(kvp.Key) = kvp.Value
        Next

        For Each kvp In combined
            Console.WriteLine($"{kvp.Key}: {kvp.Value}")
        Next
    End Sub
End Class



' run:
'
' 1: aaa
' 2: XYZ
' 3: ccc
' 4: ddd
'

 



answered Aug 25, 2025 by avibootz
0 votes
Imports System
Imports System.Collections.Generic

Class Program
    Public Shared Sub Main()
        Dim dict1 = New Dictionary(Of Integer, String) From {
            {1, "aaa"},
            {2, "bbb"}
        }
        Dim dict2 = New Dictionary(Of Integer, String) From {
            {3, "ccc"},
            {4, "ddd"},
            {2, "XYZ"}
        }
        Dim combined = New Dictionary(Of Integer, String)(dict1)

        For Each kvp In dict2

            If combined.ContainsKey(kvp.Key) Then
                combined(kvp.Key) += ", " & kvp.Value
            Else
                combined(kvp.Key) = kvp.Value
            End If
        Next

        For Each kvp In combined
            Console.WriteLine($"{kvp.Key}: {kvp.Value}")
        Next
    End Sub
End Class




' run:
'
' 1: aaa
' 2: bbb, XYZ
' 3: ccc
' 4: ddd
'

 



answered Aug 25, 2025 by avibootz
0 votes
Imports System
Imports System.Linq
Imports System.Collections.Generic

Class Program
    Public Shared Sub Main()
        Dim dict1 = New Dictionary(Of Integer, String) From {
            {1, "aaa"},
            {2, "bbb"}
        }
        Dim dict2 = New Dictionary(Of Integer, String) From {
            {3, "ccc"},
            {4, "ddd"},
            {2, "XYZ"}
        }
        Dim combined = dict1.Concat(dict2) _
						    .GroupBy(Function(kvp) kvp.Key) _
						    .ToDictionary(Function(g) g.Key, Function(g) g.Last().Value)

        For Each kvp In combined
            Console.WriteLine($"{kvp.Key}: {kvp.Value}")
        Next
    End Sub
End Class



' run:
'
' 1: aaa
' 2: XYZ
' 3: ccc
' 4: ddd
'

 



answered Aug 25, 2025 by avibootz
...