我正在尝试为我的字典编写一个合并扩展方法。
我真的很喜欢 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 是否定义了 + 运算符。一种选择是将其作为委托(delegate)传递:
public static void Merge<TKey, TValue>(this IDictionary<TKey, TValue> first
, IDictionary<TKey, TValue> second
, Func<TValue, TValue, TValue> aggregator)
{
if (second == null) return;
if (first == null) throw new ArgumentNullException("first");
foreach (var item in second)
{
if (!first.ContainsKey(item.Key))
{
first.Add(item.Key, item.Value);
}
else
{
first[item.Key] = aggregator(first[item.key], item.Value);
}
}
}
调用它看起来像:
firstDictionary.Merge(secondDictionary, (a, b) => a + b);
虽然像这样的合并操作也很常见,选择两个项目中的一个来保留,第一个或第二个(请注意,您可以使用上述函数,通过使用适当的 aggregator 实现)。
例如,要始终将项目保留在您可以使用的第一本词典中:
firstDictionary.Merge(secondDictionary, (a, b) => a);
总是用第二个替换它:
firstDictionary.Merge(secondDictionary, (a, b) => b);
