[英]How can I update dictionary element in extension methods?
我正在尝试为我的字典编写合并扩展方法。
我试图修改上面的解决方案,以便在密钥退出时更新字典项。 我不想使用Concurrent字典。 有任何想法吗 ?
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.