【发布时间】:2012-05-01 13:58:11
【问题描述】:
我有一个助手,它通过连接TValue 的ToString() 方法将两个或多个IDictionary<TKey, TValue> 对象合并为一个IDictionary<TKey, string>,如下所示:
public class DictionaryHelper<TKey, TValue>
{
public static IDictionary<TKey, string> MergeDictionaries<TKey, TValue>(params IDictionary<TKey, TValue>[] dictionaries) where TValue : class
{
var returnValue = new Dictionary<TKey, string>();
foreach (var dictionary in dictionaries)
{
foreach (var kvp in dictionary)
{
if (returnValue.ContainsKey(kvp.Key))
{
returnValue[kvp.Key] += kvp.Value.ToString();
}
else
{
returnValue[kvp.Key] = kvp.Value.ToString();
}
}
}
return returnValue;
}
}
虽然这很简单,也很容易阅读,但似乎应该有一种更有效的方法来做到这一点。有吗?
【问题讨论】:
-
记住
kvp.Valuecan benull. 高效的速度还是高效的代码行数? -
嗯...好吧,我的预期用途不允许这样做,但我同意我需要处理它。感谢您指出了这一点。高效的性能...我不介意在前面多花点力气。
-
这可能会有所帮助:stackoverflow.com/questions/712927/…
标签: c# performance