{"record":{"id":"a8bf58110faf8251","repo":"louthy/language-ext","slug":"an-element-with-the-same-key-already-exists-in-the-map","errorCode":null,"errorMessage":"An element with the same key already exists in the Map","messagePattern":"An element with the same key already exists in the Map","errorType":"exception","errorClass":"ArgumentException","httpStatus":null,"severity":"error","filePath":"LanguageExt.Core/Immutable Collections/Map/Map.Internal.cs","lineNumber":1885,"sourceCode":"        else if (cmp > 0)\n        {\n            node.Right = Add<OrdK, K, V>(node.Right, key, value, option);\n            return Balance(node);\n        }\n        else if(option == AddOpt.TryAdd)\n        {\n            // Already exists, but we don't care\n            return node;\n        }\n        else if (option == AddOpt.TryUpdate)\n        {\n            // Already exists, and we want to update the content\n            node.KeyValue = (key, value);\n            return node;\n        }\n        else\n        {\n            throw new ArgumentException(\"An element with the same key already exists in the Map\");\n        }\n    }\n\n    [MethodImpl(MethodImplOptions.AggressiveInlining)]\n    public static MapItem<K, V> Balance<K, V>(MapItem<K, V> node)\n    {\n        node.Height = (byte)(1 + Math.Max(node.Left.Height, node.Right.Height));\n        node.Count = 1 + node.Left.Count + node.Right.Count;\n\n        return node.BalanceFactor >= 2\n                   ? node.Right.BalanceFactor < 0\n                         ? DblRotLeft(node)\n                         : RotLeft(node)\n                   : node.BalanceFactor <= -2\n                       ? node.Left.BalanceFactor > 0\n                             ? DblRotRight(node)\n                             : RotRight(node)\n                       : node;","sourceCodeStart":1867,"sourceCodeEnd":1903,"githubUrl":"https://github.com/louthy/language-ext/blob/2f0e3628242889774d4141960a35671a0280051f/LanguageExt.Core/Immutable Collections/Map/Map.Internal.cs#L1867-L1903","documentation":"Deep inside MapModule's insertion logic (the Add path reached from MapInternal), the tree walk finds a node whose key compares equal to the key being added and — instead of updating — throws ArgumentException('An element with the same key already exists in the Map'). It enforces that Add is strictly insert-new; duplicates must go through SetItem/update paths.","triggerScenarios":"Calling map.Add(key, v) (or MapModule.Add) when key already exists; re-adding after a merge or bulk load that already inserted the key; ordinal-vs-culture comparisons making two string keys compare as equal here but distinct elsewhere.","commonSituations":"Seeding a Map from config/dictionary data that contains duplicate keys; idempotency retries inserting the same record twice; keys normalized differently at write vs insert time.","solutions":["Use SetItem for add-or-update semantics instead of Add when duplicates are legitimate.","Guard with Find/ContainsKey before Add and branch to SetItem on presence.","Normalize keys identically everywhere (e.g. Ord.amountOrd / ToLowerInvariant) before insertion.","Deduplicate the source data (e.g. GroupBy key, take last) before bulk-loading into the Map."],"exampleFix":"// before\nvar map2 = map.Add(key, value); // throws if key exists\n// after\nvar map2 = map.Find(key)\n    .Match(Some: _ => map.SetItem(key, value),\n           None: () => map.Add(key, value));","handlingStrategy":"validation","validationCode":"var map2 = map.ContainsKey(key)\n    ? map.SetItem(key, value)\n    : map.Add(key, value);","typeGuard":null,"tryCatchPattern":"try { var map2 = map.Add(key, value); }\ncatch (ArgumentException ex) when (ex.Message.Contains(\"same key already exists\"))\n{\n    var map2 = map.SetItem(key, value); // fall back to update\n}","preventionTips":["Use SetItem (or Find + branch) whenever the key may already exist.","Deduplicate bulk source data before loading into a Map.","Apply identical key normalization (ordinal comparison, casing) everywhere.","Account for retry/idempotency flows that may re-insert the same key."],"tags":["csharp","languageext","map","duplicate-key"],"backgroundTag":"invalid-argument-value","analyzedSha":"2f0e3628242889774d4141960a35671a0280051f","analyzedAt":"2026-09-15T03:31:55.716Z","contentChangedAt":"2026-09-15T03:31:55.716Z","schemaVersion":2},"datasetVersion":"2026-09-16T09:17:16.951Z"}