简体   繁体   English

如何在扩展方法中更新字典元素?

[英]How can I update dictionary element in extension methods?

I am trying to write an merge extension methods for my dictionary. 我正在尝试为我的字典编写合并扩展方法。

I really like the solution Merging dictionaries in C# 我真的很喜欢在C#中合并字典解决方案

I am trying to modify the above solution to update the dictionary item if key exits. 我试图修改上面的解决方案,以便在密钥退出时更新字典项。 I do not want to use Concurrent dictionary. 我不想使用Concurrent字典。 Any ideas ? 有任何想法吗 ?

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**
                }
            }
        }

Well, if you want the result to contain both values you need some means of combining them. 好吧,如果你想让结果包含两个值,你需要一些方法来组合它们。 If you want to "Add" the values then you'll need to define some means of combining two items, because you can't know if TValue defines a + operator. 如果你想“添加”这些值,那么你需要定义一些组合两个项目的方法,因为你不知道TValue定义了一个+运算符。 One option is to pass it in as a 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);
        }
    }
}

To call it would look like: 打电话看起来像:

firstDictionary.Merge(secondDictionary, (a, b) => a + b);

Although it's also common for Merge operations like this to pick one of the two items to keep, either the first, or the second (note that you could do either using the above function, by using the appropriate aggregator implementation). 虽然像这样的Merge操作通常选择要保留的两个项目之一,或者第一个或第二个(注意您可以使用上述函数,通过使用适当的aggregator实现)。

For example, to always keep the item in the first dictionary you can use: 例如,要始终将项目保留在第一个字典中,您可以使用:

firstDictionary.Merge(secondDictionary, (a, b) => a);

To always replace it with the second: 要始终用第二个替换它:

firstDictionary.Merge(secondDictionary, (a, b) => b);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM