{"record":{"id":"7d566a8245f0bb58","repo":"TheAlgorithms/C-Sharp","slug":"key-key-already-exists-in-b-tree","errorCode":null,"errorMessage":"Key \"{key}\" already exists in B-Tree.","messagePattern":"Key \"(.+?)\" already exists in B-Tree\\.","errorType":"exception","errorClass":"ArgumentException","httpStatus":null,"severity":"error","filePath":"DataStructures/BTree/BTree.cs","lineNumber":375,"sourceCode":"\n    /// <summary>\n    ///     Insert a key into a leaf node.\n    /// </summary>\n    /// <param name=\"node\">Leaf node to insert into.</param>\n    /// <param name=\"key\">Key to insert.</param>\n    private void InsertIntoLeaf(BTreeNode<TKey> node, TKey key)\n    {\n        var i = node.KeyCount - 1;\n\n        while (i >= 0 && comparer.Compare(key, node.Keys[i]) < 0)\n        {\n            node.Keys[i + 1] = node.Keys[i];\n            i--;\n        }\n\n        if (i >= 0 && comparer.Compare(key, node.Keys[i]) == 0)\n        {\n            throw new ArgumentException($\"\"\"Key \"{key}\" already exists in B-Tree.\"\"\");\n        }\n\n        node.Keys[i + 1] = key;\n        node.KeyCount++;\n    }\n\n    /// <summary>\n    ///     Insert a key into a non-leaf node.\n    /// </summary>\n    /// <param name=\"node\">Non-leaf node to insert into.</param>\n    /// <param name=\"key\">Key to insert.</param>\n    private void InsertIntoNonLeaf(BTreeNode<TKey> node, TKey key)\n    {\n        var i = FindInsertionIndex(node, key);\n\n        if (node.Children[i]!.IsFull())\n        {\n            SplitChild(node, i);","sourceCodeStart":357,"sourceCodeEnd":393,"githubUrl":"https://github.com/TheAlgorithms/C-Sharp/blob/96e2905cab7bc6b33ac0a34ee5bb82ddccbcbb6c/DataStructures/BTree/BTree.cs#L357-L393","documentation":"BTree.InsertIntoLeaf throws ArgumentException when the key being inserted compares equal to an existing key in the leaf. B-Tree here requires unique keys, so a duplicate Insert is rejected rather than overwriting the existing value. The check runs as part of the leaf insertion loop (`i >= 0 && comparer.Compare(key, node.Keys[i]) == 0`).","triggerScenarios":"Calling BTree.Insert(key, value) with a key that already exists anywhere in the tree; the duplicate eventually lands in a leaf via InsertNonFull and matches the neighbor key during the shift-down loop.","commonSituations":"Re-inserting the same record ID; importing a dataset with repeated keys; idempotent upsert code written against a Set-like structure that actually requires unique keys; custom comparer that treats distinct keys as equal (e.g., case-insensitive string comparer).","solutions":["Check Contains/TryGetValue first and skip or update instead of inserting duplicates","Use a dictionary keyed by the B-Tree key to dedupe before batch insertion","Catch ArgumentException with Message.Contains(\"already exists\") if duplicates are expected and ignorable","If keys are genuinely distinct, verify the custom comparer does not collapse them to 0"],"exampleFix":"// before\ntree.Insert(key, value); // throws on duplicate key\n// after\nif (!tree.Contains(key))\n{\n    tree.Insert(key, value);\n}\nelse\n{\n    // handle duplicate (skip, log, or update)\n}","handlingStrategy":"validation","validationCode":"if (tree.Contains(key)) { /* skip or update */ } else { tree.Insert(key, value); }","typeGuard":"null","tryCatchPattern":"try { tree.Insert(key, value); } catch (ArgumentException ex) when (ex.Message.Contains(\"already exists\")) { /* duplicate: skip/log */ }","preventionTips":["Deduplicate keys before bulk insert","Never assume upsert semantics; check Contains first","Audit custom comparers for unwanted equality collisions"],"tags":["csharp","btree","duplicate-key"],"backgroundTag":"file-already-exists","analyzedSha":"96e2905cab7bc6b33ac0a34ee5bb82ddccbcbb6c","analyzedAt":"2026-09-13T17:04:01.438Z","contentChangedAt":"2026-09-13T17:04:01.438Z","schemaVersion":2},"datasetVersion":"2026-09-16T04:17:20.429Z"}