TheAlgorithms/C-Sharp · error · ArgumentException

Key " " already exists in B-Tree.

Error message

Key "{key}" already exists in B-Tree.

What it means

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`).

Solutions

  1. Check Contains/TryGetValue first and skip or update instead of inserting duplicates
  2. Use a dictionary keyed by the B-Tree key to dedupe before batch insertion
  3. Catch ArgumentException with Message.Contains("already exists") if duplicates are expected and ignorable
  4. If keys are genuinely distinct, verify the custom comparer does not collapse them to 0

Example fix

// before
tree.Insert(key, value); // throws on duplicate key
// after
if (!tree.Contains(key))
{
    tree.Insert(key, value);
}
else
{
    // handle duplicate (skip, log, or update)
}
Defensive patterns

Strategy: validation

Validate before calling

if (tree.Contains(key)) { /* skip or update */ } else { tree.Insert(key, value); }

Type guard

null

Try / catch

try { tree.Insert(key, value); } catch (ArgumentException ex) when (ex.Message.Contains("already exists")) { /* duplicate: skip/log */ }

Prevention

When it happens

Trigger: 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.

Common situations: 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).

Understand the failure class

Background: "already exists" / EEXIST / FileAlreadyExistsException: what the 'file already exists' error means and how to fix it — this error's family across 37 libraries.

Related errors


AI-assisted analysis of TheAlgorithms/C-Sharp@96e2905cab (2026-09-13). Data as JSON: /api/errors/7d566a8245f0bb58. Report an issue: GitHub.

Appendix: source

Thrown at DataStructures/BTree/BTree.cs:375

    /// <summary>
    ///     Insert a key into a leaf node.
    /// </summary>
    /// <param name="node">Leaf node to insert into.</param>
    /// <param name="key">Key to insert.</param>
    private void InsertIntoLeaf(BTreeNode<TKey> node, TKey key)
    {
        var i = node.KeyCount - 1;

        while (i >= 0 && comparer.Compare(key, node.Keys[i]) < 0)
        {
            node.Keys[i + 1] = node.Keys[i];
            i--;
        }

        if (i >= 0 && comparer.Compare(key, node.Keys[i]) == 0)
        {
            throw new ArgumentException($"""Key "{key}" already exists in B-Tree.""");
        }

        node.Keys[i + 1] = key;
        node.KeyCount++;
    }

    /// <summary>
    ///     Insert a key into a non-leaf node.
    /// </summary>
    /// <param name="node">Non-leaf node to insert into.</param>
    /// <param name="key">Key to insert.</param>
    private void InsertIntoNonLeaf(BTreeNode<TKey> node, TKey key)
    {
        var i = FindInsertionIndex(node, key);

        if (node.Children[i]!.IsFull())
        {
            SplitChild(node, i);

View on GitHub (pinned to 96e2905cab)