views:

57

answers:

2

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?

+7  A: 

In .Net 4.0:

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

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

SLaks
Beat by a second T_T --- good solution, quite fast and very easy to read.
mafutrct
+2  A: 

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));
        }
    }
Adam