fork download
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4.  
  5. public class Test
  6. {
  7. public static void Main()
  8. {
  9. Dictionary<int, int> dic1 = new Dictionary<int, int>() { {24379,349}, { 24368, 348 }, { 24377, 91 }, { 24366, 90 } };
  10. Dictionary<int, int> dic2 = new Dictionary<int, int>() { { 24379, 270451 }, { 24368, 270451 }, { 24377, 270450 }, { 24366, 270450 } };
  11. var a = OpAdd(dic1, dic2);
  12. var b = AnsAdd(dic1, dic2);
  13. Console.WriteLine("OP's results");
  14. Show(a);
  15. Console.WriteLine("Answer's answer");
  16. Show(b);
  17. }
  18. private static Dictionary<int, int> OpAdd(Dictionary<int, int> dict1, Dictionary<int, int> dict2) {
  19. Dictionary<int, int> result = new Dictionary<int, int>();
  20. foreach (int itemKey in dict1.Keys)
  21. {
  22. result.Add (
  23. itemKey
  24. , dict1.Where(a => dict2.ContainsKey(a.Key)
  25. && dict2.ContainsKey(itemKey)
  26. && dict2[a.Key] == dict2[itemKey])
  27. .Sum(a => a.Value)
  28. );
  29. }
  30. return result;
  31. }
  32.  
  33. private static Dictionary<int, int> AnsAdd(Dictionary<int, int> dict1, Dictionary<int, int> dict2)
  34. {
  35. var lookup = dict1
  36. .Where(p => dict2.ContainsKey(p.Key))
  37. .GroupBy(p => dict2[p.Key])
  38. .ToDictionary(g => g.Key, g => g.Sum(p => p.Value));
  39. return dict1.Keys
  40. .Where(k => dict2.ContainsKey(k))
  41. .ToDictionary(k => k, k => lookup[dict2[k]]);
  42. }
  43.  
  44. private static void Show(IDictionary<int,int> d) {
  45. foreach(var p in d.OrderBy(x => x.Key)) {
  46. Console.WriteLine("{0} : {1}", p.Key, p.Value);
  47. }
  48. Console.WriteLine("-----------");
  49. }
  50. }
Success #stdin #stdout 0.01s 30064KB
stdin
Standard input is empty
stdout
OP's results
24366 : 181
24368 : 697
24377 : 181
24379 : 697
-----------
Answer's answer
24366 : 181
24368 : 697
24377 : 181
24379 : 697
-----------