Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET: efficient way to produce a string from a Dictionary<K,V>?

Suppose I have a Dictionary<String,String>, and I want to produce a string representation of it. The "stone tools" way of doing it would be:

private static string DictionaryToString(Dictionary<String,String> hash)
{
    var list = new List<String> ();
    foreach (var kvp in hash)
    {
        list.Add(kvp.Key + ":" + kvp.Value);
    }
    var result = String.Join(", ", list.ToArray());
    return result;
}

Is there an efficient way to do this in C# using existing extension methods?

I know about the ConvertAll() and ForEach() methods on List, that can be used to eliminate foreach loops. Is there a similar method I can use on Dictionary to iterate through the items and accomplish what I want?

like image 246
Cheeso Avatar asked May 12 '10 14:05

Cheeso


2 Answers

Here you go:


    public static class DictionaryExtensions
    {
        public static string DictionaryToString(this Dictionary<String, String> hash)
        {
            return String.Join(", ", hash.Select(kvp => kvp.Key + ":" + kvp.Value));
        }
    }
like image 72
Adam Avatar answered Sep 27 '22 17:09

Adam


In .Net 4.0:

String.Join(", ", hash.Select(kvp => kvp.Key + ":" + kvp.Value));

In .Net 3.5, you'll need to add .ToArray().

like image 36
SLaks Avatar answered Sep 27 '22 16:09

SLaks