【发布时间】:2013-02-15 07:00:29
【问题描述】:
我正在尝试为我的字典编写一个合并扩展方法。
我真的很喜欢solution Merging dictionaries in C#
我正在尝试修改上述解决方案以在键退出时更新字典项。我不想使用并发字典。有什么想法吗?
public static void Merge<TKey, TValue>(this IDictionary<TKey, TValue> first, IDictionary<TKey, TValue> second)
{
if (second == null) return;
if (first == null) first = new Dictionary<TKey, TValue>();
foreach (var item in second)
{
if (!first.ContainsKey(item.Key))
{
first.Add(item.Key, item.Value);
}
else
{
**//I Need to perform following update . Please Help
//first[item.Key] = first[item.key] + item.Value**
}
}
}
【问题讨论】:
-
您应该提供一些示例输入和预期输出。
-
这完全取决于您对任意
TValue的“合并”是什么意思。数字类型可以以与字符串或任意对象大不相同的方式合并。一种选择是提供merge委托作为参数,以便调用者可以指定应如何合并重复键的值。
标签: c# dictionary merge updates