Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flatten Dictionary to Comma Delimited List of Set of Key/Value Pairs

Tags:

c#

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"

like image 699
PositiveGuy Avatar asked Sep 15 '25 06:09

PositiveGuy


2 Answers

This is pretty easy using Linq:

string.Join(", ", fields.Select(kvp => kvp.Key + " " + kvp.Value));
like image 184
Bas Avatar answered Sep 17 '25 19:09

Bas


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.

like image 30
Sergey Berezovskiy Avatar answered Sep 17 '25 20:09

Sergey Berezovskiy