最有效的字典< K,V>的ToString()与格式? [英] Most efficient Dictionary<K,V>.ToString() with formatting?

查看:275
本文介绍了最有效的字典< K,V>的ToString()与格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是字典转换为格式化字符串的最有效方法。

What's the most efficient way to convert a Dictionary to a formatted string.

例如:

我的方法:

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?

注:字典最多有10个项目,我不承诺使用它,如果另一个类似键 - 值对对象类型存在

此外,由于我返回一个字符串,无论如何,将仿制药是什么样子?

Also, since I'm returning strings anyhow, what would a generic version look like?

推荐答案

我只是改写了你的版本是有点更通用,并使用的StringBuilder

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

这篇关于最有效的字典&LT; K,V&GT;的ToString()与格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆