I am fairly new to C#. I would like to "add" two Dictionaries together using parallelism.
Example:
Dictionary<string, int> dict1 = new()
{
{ "a", 1 },
{ "b", 2 },
{ "c", 3 },
//...
};
Dictionary<string, int> dict2 = new()
{
{ "a", 1 },
{ "b", 2 },
{ "c", 3 },
//...
};
Result of dict1 + dict2
:
Dictionary<string, int> dict3 = new()
{
{ "a", 2 },
{ "b", 4 },
{ "c", 6 },
//...
};
I currently have a solution where I wrap a Dictionary<string, int>
in my Modifier
class:
public class Modifier
{
public Dictionary<string, int> modifier = new Dictionary<string, int>();
public void Add(string key, int value){
modifier.Add(key, value);
}
public bool ContainsKey(string key){
return modifier.ContainsKey(key);
}
public int this[string key]{
get => modifier[key];
set => modifier[key] = value;
}
public static Modifier operator +(Modifier a, Modifier b){
foreach (string key in b.modifier.Keys){
if (a.ContainsKey(key)){
a[key] += b[key];
} else {
a.Add(key, b[key]);
}
}
return a;
}
}
To add, I do Modifier result = a + b
(where a
and b
are Modifier
objects). However, for my application, I will be doing many of these "additions" on large dictionaries and am afraid it will not scale well.
I am not very familiar with C# parallel programming. I thought about splitting the keys into equal sub-groups and performing the addition one each group, but I am not quite sure how to implement it, or even if it is optimal.
What is the most efficient way to do this addition?