I have a dictionary such as:
var fields = new Dictionary<string, string>
{
{"2", "34"},
{"4", "45"}
};
And I want to know if there's an easier way than creating a loop ans string builder to essentially create this in the end: "key value, key value, key value"..
So for this dictionary I'd want to flatten it out to a string like this where it's comma seperated between each set and each set has a space between key and value: "2 34, 4 45"
This is pretty easy using Linq:
string.Join(", ", fields.Select(kvp => kvp.Key + " " + kvp.Value));
Select formatted strings which contain key and value of each KeyValuePair, then join them with comma:
var result = String.Join(", ", fields.Select(kvp =>
String.Format("{0} {1}", kvp.Key, kvp.Value)));
Alternative solution - aggregate KeyValuePair values with single StringBuilder:
var builder = fields.Aggregate(new StringBuilder(),
(sb, kvp) => sb.AppendFormat("{0} {1}, ", kvp.Key, kvp.Value));
if (builder.Length > 0)
builder.Remove(builder.Length - 2, 2);
var result = builder.ToString();
Thus you will avoid creation of additional strings for each KeyValuePair.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With