How to combine all keys and values from a dictionary into a single string in C#

1 Answer

0 votes
using System;
using System.Collections.Generic;

class Program
{
    // Function to combine keys and values into a single string
    static string CombineKeysAndValues(Dictionary<string, string> dictionary) {
        var combinedString = new System.Text.StringBuilder();

        foreach (var kvp in dictionary) {
            combinedString.Append(kvp.Key)
                          .Append("=")
                          .Append(kvp.Value)
                          .Append(", ");
        }

        // Remove the trailing comma and space
        if (combinedString.Length > 0) {
            combinedString.Length -= 2;
        }

        return combinedString.ToString();
    }

    static void Main()
    {
        var dictionary = new Dictionary<string, string>
        {
            { "Key1", "Value1" },
            { "Key2", "Value2" },
            { "Key3", "Value3" },
            { "Key4", "Value4" }
        };

        // Combine the keys and values
        string result = CombineKeysAndValues(dictionary);

        Console.WriteLine("Combined keys and values: " + result);
    }
}


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

 



answered Mar 31 by avibootz
edited Mar 31 by avibootz
...