最有效的Dictionary <K,V> .ToString()格式化?

Arm*_*est 10 .net c# dictionary tostring type-conversion

将Dictionary转换为格式化字符串的最有效方法是什么.

例如:

我的方法:

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;
}
Run Code Online (Sandbox Code Playgroud)

是否有更好/更简洁/更有效的方式?

注意:字典最多有10个项目,如果存在另一个类似的"键值对"对象类型,我就不会使用它

另外,既然我无论如何都会返回字符串,那么通用版本会是什么样子?

Gab*_*abe 23

我只是重写了你的版本,使其更具通用性并使用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(); 
}
Run Code Online (Sandbox Code Playgroud)


Lee*_*Lee 16

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();
}
Run Code Online (Sandbox Code Playgroud)


aba*_*hev 9

这种方法

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)));
}
Run Code Online (Sandbox Code Playgroud)

使用下一个方式:

dic.ToFormattedString(null, null); // default format and separator
Run Code Online (Sandbox Code Playgroud)

将转换

new Dictionary<string, string>
{
    { "a", "1" },
    { "b", "2" }
};
Run Code Online (Sandbox Code Playgroud)

a='1' b='2'
Run Code Online (Sandbox Code Playgroud)

要么

dic.ToFormattedString("{0}={1}", ", ")
Run Code Online (Sandbox Code Playgroud)

a=1, b=2
Run Code Online (Sandbox Code Playgroud)

不要忘记过载:

public static string ToFormattedString<TKey, TValue>(this IDictionary<TKey, TValue> dic)
{
    return dic.ToFormattedString(null, null);
}
Run Code Online (Sandbox Code Playgroud)

您可以使用generic TKey/,TValue因为任何对象都ToString()将使用String.Format().

并且只要IDictionary<TKey, TValue>IEnumerable<KeyValuePair<TKey, TValue>>你可以使用任何.我更喜欢IDictionary以获得更多的代码表现力.