Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most efficient Dictionary<K,V>.ToString() with formatting?

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?

like image 433
Armstrongest Avatar asked Sep 03 '10 19:09

Armstrongest


3 Answers

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(); 
}
like image 116
Gabe Avatar answered Sep 19 '22 21:09

Gabe


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();
}
like image 28
Lee Avatar answered Sep 19 '22 21:09

Lee


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.

like image 41
abatishchev Avatar answered Sep 21 '22 21:09

abatishchev