【问题标题】:How can I update dictionary element in extension methods?如何更新扩展方法中的字典元素?
【发布时间】: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


【解决方案1】:

好吧,如果您希望结果包含两个值,您需要一些组合它们的方法。如果你想“添加”这些值,那么你需要定义一些组合两个项目的方法,因为你不知道 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);

【讨论】:

  • Servy,非常感谢您的解决方案。那是一个非常快速的反应。我真的很感激。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多