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?
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));
}
}
In .Net 4.0:
String.Join(", ", hash.Select(kvp => kvp.Key + ":" + kvp.Value));
In .Net 3.5, you'll need to add .ToArray()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With