[c#] Convert Dictionary<string,string> to semicolon separated string in c#

Simple one to start the day, given a Dictionary<string, string> as follows:

var myDict = new Dictionary<string, string>();
myDict["A"] = "1";
myDict["B"] = "2";
myDict["C"] = "3";
myDict["D"] = "4";

I wish to create a string: "A=1;B=2;C=3;D=4"

An example implementation:

var myStringBuilder = new StringBuilder();
bool first = true;
foreach (KeyValuePair<string, string> pair in myDict)
{
    if (first)
    {
        first = false;
    }
    else
    {
        myStringBuilder.Append(";");
    }

    myStringBuilder.AppendFormat("{0}={1}", pair.Key, pair.Value);
}

var myDesiredOutput = myStringBuilder.ToString();

Note the dictionary is likely to have less than 10 items which suggests that a StringBuilder is overkill.

What alternative implementations are more succinct / efficient? Does the framework have any features that will help?

This question is related to c#

The answer is



Another option is to use the Aggregate extension rather than Join:

String s = myDict.Select(x => x.Key + "=" + x.Value).Aggregate((s1, s2) => s1 + ";" + s2);

For Linq to work over Dictionary you need at least .Net v3.5 and using System.Linq;.

Some alternatives:

string myDesiredOutput = string.Join(";", myDict.Select(x => string.Join("=", x.Key, x.Value)));

or

string myDesiredOutput = string.Join(";", myDict.Select(x => $"{x.Key}={x.Value}"));

If you can't use Linq for some reason, use Stringbuilder:

StringBuilder sb = new StringBuilder();
var isFirst = true;
foreach(var x in myDict) 
{
  if (isFirst) 
  {
    sb.Append($"{x.Key}={x.Value}");
    isFirst = false;
  }
  else
    sb.Append($";{x.Key}={x.Value}"); 
}

string myDesiredOutput = sb.ToString(); 

myDesiredOutput:

A=1;B=2;C=3;D=4