我有两个字典。如果dict2中的值相同,则需要将dict1中匹配键的值相加,并在结果字典中生成结果,如下所示。
**dict1** **dict2**
Id value Id value
24379 348 24379 270451
24368 348 24368 270451
24377 90 24377 270450
24366 90 24366 270450
24369 10 24369 270450
24300 25
Result:
24379 696
24368 696
24377 190
24366 190
24369 190
我有以下逻辑,希望优化此解决方案:
Dictionary<int, int> result = new Dictionary<int, int>();
foreach (int itemKey in dict1.keys)
{
result.add (itemKey, dict1.Where(a => dict2.ContainsKey(a.key)
&& dict2.ContiansKey(itemKey)
&& dict2[a.key] == dict2[itemKey])
.Sum(a => a.value);
}
dict2
中24379
和24368
的值都是270451
,所以 OP 从dict1
中加起来的值也都是348
。 - Sergey Kalinichenko