I have two collections that I want to intersect, and perform a sum operation on matching elements.
For example the collections are (in pseudo code):
col1 = { {"A", 5}, {"B", 3}, {"C", 2} }
col2 = { {"B", 1}, {"C", 8}, {"D", 6} }
and the desired result is:
intersection = { {"B", 4}, {"C", 10} }
I know how to use an IEqualityComparer to match the elements on their name, but how to sum the values while doing the intersection?
EDIT:
The starting collections haven’t two items with the same name.
Let’s say your input data looks like this:
If the strings are unique in each sequence (i.e there can be no more than a single {“A”, XXX} in either sequence) you can
joinlike this:You might also want to consider using a
group by, which would be more appropriate if this uniqueness doesn’t hold:If neither is what you want, please clarify your requirements more precisely.
EDIT: After your clarification that these are dictionaries – your existing solution is perfectly fine. Here’s another alternative with
join:or in fluent syntax: