如何在扩展方法中更新字典元素
本文关键字:更新 字典 元素 方法 扩展 | 更新日期: 2023-09-27 18:01:42
我正试图为我的字典写一个合并扩展方法。
我真的很喜欢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
是否定义了一个+运算符。一种方法是将其作为委托传递:
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);
虽然像这样的Merge操作选择保留两个项中的一个也很常见,要么是第一个,要么是第二个(请注意,通过使用适当的aggregator
实现,您可以使用上述函数中的任何一个)。
例如,要始终将项保存在第一个字典中,可以使用:
firstDictionary.Merge(secondDictionary, (a, b) => a);
总是用第二个:
firstDictionary.Merge(secondDictionary, (a, b) => b);