What's the most efficient way to convert a Dictionary to a formatted string.
e.g.:
My method:
public string DictToString(Dictionary<string, string> items, string format){
format = String.IsNullOrEmpty(format) ? "{0}='{1}' " : format;
string itemString = "";
foreach(var item in items){
itemString = itemString + String.Format(format,item.Key,item.Value);
}
return itemString;
}
Is there a better/more concise/more efficient way?
Note: the Dictionary will have at most 10 items and I'm not committed to using it if another similar "key-value pair" object type exists
Also, since I'm returning strings anyhow, what would a generic version look like?
I just rewrote your version to be a bit more generic and use StringBuilder
:
public string DictToString<T, V>(IEnumerable<KeyValuePair<T, V>> items, string format)
{
format = String.IsNullOrEmpty(format) ? "{0}='{1}' " : format;
StringBuilder itemString = new StringBuilder();
foreach(var item in items)
itemString.AppendFormat(format, item.Key, item.Value);
return itemString.ToString();
}
public string DictToString<TKey, TValue>(Dictionary<TKey, TValue> items, string format)
{
format = String.IsNullOrEmpty(format) ? "{0}='{1}' " : format;
return items.Aggregate(new StringBuilder(), (sb, kvp) => sb.AppendFormat(format, kvp.Key, kvp.Value)).ToString();
}
This method
public static string ToFormattedString<TKey, TValue>(this IDictionary<TKey, TValue> dic, string format, string separator)
{
return String.Join(
!String.IsNullOrEmpty(separator) ? separator : " ",
dic.Select(p => String.Format(
!String.IsNullOrEmpty(format) ? format : "{0}='{1}'",
p.Key, p.Value)));
}
used next way:
dic.ToFormattedString(null, null); // default format and separator
will convert
new Dictionary<string, string>
{
{ "a", "1" },
{ "b", "2" }
};
to
a='1' b='2'
or
dic.ToFormattedString("{0}={1}", ", ")
to
a=1, b=2
Don't forget an overload:
public static string ToFormattedString<TKey, TValue>(this IDictionary<TKey, TValue> dic)
{
return dic.ToFormattedString(null, null);
}
You can use generic TKey
/TValue
because any object has ToString()
which will be used by String.Format()
.
And as far as IDictionary<TKey, TValue>
is IEnumerable<KeyValuePair<TKey, TValue>>
you can use any. I prefer IDictionary for more code expressiveness.
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