Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to convert Dictionary<string, string> into single aggregate String representation?

Tags:

How would I convert a dictionary of key value pairs into a single string? Can you do this using LINQ aggregates? I've seen examples on doing this using a list of strings, but not a dictionary.

Input:

Dictionary<string, string> map = new Dictionary<string, string> {            {"A", "Alpha"},             {"B", "Beta"},            {"G", "Gamma"} }; 

Output:

  string result = "A:Alpha, B:Beta, G:Gamma"; 
like image 698
SliverNinja - MSFT Avatar asked Nov 03 '11 21:11

SliverNinja - MSFT


People also ask

How do I convert a string to a dictionary?

To convert a Python string to a dictionary, use the json. loads() function. The json. loads() is a built-in Python function that converts a valid string to a dict.

Can we convert string to dictionary in Python?

You can easily convert python string to the dictionary by using the inbuilt function of loads of json library of python. Before using this method, you have to import the json library in python using the “import” keyword.


2 Answers

This is the most concise way I can think of:

var result = string.Join(", ", map.Select(m => m.Key + ":" + m.Value).ToArray()); 

If you are using .NET 4+ you can drop the .ToArray():

var result = string.Join(", ", map.Select(m => m.Key + ":" + m.Value)); 

And if you are able to use the newish string interpolation language feature:

var result = string.Join(", ", map.Select(m => $"{m.Key}:{m.Value}")); 

However, depending on your circumstances, this might be faster (although not very elegant):

var result = map.Aggregate(new StringBuilder(),     (a, b) => a.Append(", ").Append(b.Key).Append(":").Append(b.Value),     (a) => a.Remove(0, 2).ToString()); 

I ran each of the above with a varying number of iterations (10,000; 1,000,000; 10,000,000) on your three-item dictionary and on my laptop, the latter was on average 39% faster. On a dictionary with 10 elements, the latter was only about 22% faster.

One other thing to note, simple string concatenation in my first example was about 38% faster than the string.Format() variation in mccow002's answer, as I suspect it's throwing in a little string builder in place of the concatenation, given the nearly identical performance metrics.

To recreate the original dictionary from the result string, you could do something like this:

var map = result.Split(',')     .Select(p => p.Trim().Split(':'))     .ToDictionary(p => p[0], p => p[1]); 
like image 76
Cᴏʀʏ Avatar answered Oct 23 '22 19:10

Cᴏʀʏ


string result = string.Join(", ", map.Select(x => string.Format("{0}:{1}", x.Key, x.Value)).ToArray()) 
like image 25
mccow002 Avatar answered Oct 23 '22 21:10

mccow002