Convert Dictionary<string,string> to semicolon separated string in c#
using System.Linq;
string s = string.Join(";", myDict.Select(x => x.Key + "=" + x.Value).ToArray());
(And if you're using .NET 4, or newer, then you can omit the final ToArray
call.)
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