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";
This is the most concise way I can think of:
If you are using .NET 4+ you can drop the
.ToArray():And if you are able to use the newish string interpolation language feature:
However, depending on your circumstances, this might be faster (although not very elegant):
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: