How to combine all keys and values from a dictionary into a single string in VB.NET

1 Answer

0 votes
Imports System
Imports System.Collections.Generic

Public Class Program
    Public Shared Function CombineKeysAndValues(ByVal dictionary As Dictionary(Of String, String)) As String
        Dim combinedString = New System.Text.StringBuilder()

        For Each kvp In dictionary
            combinedString.Append(kvp.Key).Append("=").Append(kvp.Value).Append(", ")
        Next
		
		' Remove the trailing comma and space
        If combinedString.Length > 0 Then
            combinedString.Length -= 2
        End If

        Return combinedString.ToString()
    End Function

	Public Shared Sub Main()
        Dim dictionary = New Dictionary(Of String, String) From {
            {"Key1", "Value1"},
            {"Key2", "Value2"},
            {"Key3", "Value3"},
            {"Key4", "Value4"}
        }
        Dim result As String = CombineKeysAndValues(dictionary)
	
        Console.WriteLine("Combined keys and values: " & result)
    End Sub
End Class


 
' run:
'
' Combined keys and values: Key1=Value1, Key2=Value2, Key3=Value3, Key4=Value4 
'

 



answered Mar 31, 2025 by avibootz
edited Mar 31, 2025 by avibootz
...