[英]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.