louthy/language-ext · error · ArgumentException

Key not found in set

Error message

Key not found in set

What it means

This ArgumentException is a lookup guard in Set.Internal's Find<OrdK, K>: when the recursive search reaches an empty node the key is absent, and since Find must return a K (not an Option), it throws instead of returning a default. The faulting input is a key that is not in the set; callers should use Contains or TryFind first.

Solutions

  1. Use set.Find(key) returning Option<K> / TryFind instead of the throwing Find
  2. Check set.Contains(key) before Find
  3. Use the same Ord instance for lookup as was used for insertion

Example fix

// before
var v = set.Find(key); // throws if absent
// after
set.Find(key).IfSome(v => ...); // Option-based lookup
Defensive patterns

Strategy: fallback

Validate before calling

if (set.Contains(key)) { var v = Set.find(key, set); }

Try / catch

K v;
try { v = Set.find(key, set); }
catch (ArgumentException) { v = default; } // or Option-based lookup

Prevention

When it happens

Trigger: Set.Find (find) called with a key that is not in the set, including lookups on an empty set; also triggered by comparer mismatch making the key 'unfindable'.

Common situations: Searching for a value never inserted, lookup key differing in case/culture from the stored one, or an Ord type argument different from the one used when inserting.

Related errors


AI-assisted analysis of louthy/language-ext@2f0e362824 (2026-09-15). Data as JSON: /api/errors/655eb0ed4305cb10. Report an issue: GitHub.

Appendix: source

Thrown at LanguageExt.Core/Immutable Collections/Set/Internal/Set.Internal.cs:1092

        {
            return Contains<OrdK, K>(node.Left, key);
        }
        else if (cmp > 0)
        {
            return Contains<OrdK, K>(node.Right, key);
        }
        else
        {
            return true;
        }
    }

    [Pure]
    public static K Find<OrdK, K>(SetItem<K> node, K key) where OrdK : Ord<K>
    {
        if (node.IsEmpty)
        {
            throw new ArgumentException("Key not found in set");
        }
        var cmp = OrdK.Compare(key, node.Key);
        if (cmp < 0)
        {
            return Find<OrdK, K>(node.Left, key);
        }
        else if (cmp > 0)
        {
            return Find<OrdK, K>(node.Right, key);
        }
        else
        {
            return node.Key;
        }
    }

    /// <summary>
    /// TODO: I suspect this is suboptimal, it would be better with a custom Enumerator 

View on GitHub (pinned to 2f0e362824)