Most efficient Dictionarylt;K,Vgt;.ToString() with formatting?(最有效的 Dictionarylt;K,Vgt;.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();
}
这篇关于最有效的 Dictionary<K,V>.ToString() 格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:最有效的 Dictionary<K,V>.ToString() 格式?
- 带问号的 nvarchar 列结果 2022-01-01
- 为什么 C# 中的堆栈大小正好是 1 MB? 2022-01-01
- 在 LINQ to SQL 中使用 contains() 2022-01-01
- Windows 喜欢在 LINUX 中使用 MONO 进行服务开发? 2022-01-01
- 在 C# 中异步处理项目队列 2022-01-01
- Azure Active Directory 与 MVC,客户端和资源标识同一 2022-01-01
- 是否可以在 .Net 3.5 中进行通用控件? 2022-01-01
- CanBeNull和ReSharper-将其用于异步任务? 2022-01-01
- C# 通过连接字符串检索正确的 DbConnection 对象 2022-01-01
- 使用 rss + c# 2022-01-01