Skip to content

OrderedCollection.IndexOf(x) returns the index of a different element with the same key, so RemoveAt(IndexOf(x)) removes the wrong item #107

Closed

Description

@matt-edmondson

What's wrong

The fix for #62 (commit afb5ecc) made OrderedCollection<T>.Remove(item) pick, among the run of elements that compare equal to item, the one that also Equals it. IndexOf(item) was not changed: it still returns FindFirst(item), the first element that merely compares equal (Containers/OrderedCollection.cs:329-333).

The two methods now disagree about which element "x" is whenever a key-based comparer is used.

Failure scenario

The comparer orders by Priority. Add a (Priority 1) and then b (Priority 1), giving [a, b].

  • Remove(b) removes index 1. This is correct.
  • IndexOf(b) returns 0, but collection[0] is a.
  • RemoveAt(IndexOf(b)) therefore removes a, and b stays in the collection.

The XML doc on IndexOf promises "the index of the first occurrence of the specified element", and a is not that element. IList<T>-style callers that look an item up and then act on its index (RemoveAt, this[i] = …) operate on the wrong element.

Suggested fix

  • Move Remove's run scan into a private helper, for example FindMatchIndex(item). It takes the lower bound, scans the run of elements that compare equal for one that EqualityComparer<T>.Default.Equals the item, and falls back to the first match if none does.
  • Use the helper in both IndexOf and Remove. Keeping the fallback preserves the guarantee that Contains(x) being true implies IndexOf(x) >= 0.

Acceptance criteria

  • IndexOf returns the index of the element that Equals the argument when one exists in the equal-key run.
  • A test covers a key comparer with duplicate keys: IndexOf(b) returns the index of b.
  • A test asserts that IndexOf(x) and Remove(x) target the same index.

Activity

  1. added
    bug
    on Oct 6, 2026
  2. matt-edmondson commented on Oct 6, 2026

    @matt-edmondson
    ContributorAuthor

    Triage

    • Category: Bug
    • Priority: High. With a key-based comparer and duplicate keys, RemoveAt(IndexOf(x)) and this[IndexOf(x)] = … act on the wrong element, which silently corrupts collection contents. IndexOf and Remove now disagree about which element "x" is.
    • Area / suggested owner: Containers/OrderedCollection.cs (IndexOf / Remove).
    • Duplicates / in progress: Follows on from the closed OrderedCollection<T>.IndexOf returns an arbitrary duplicate instead of the documented first occurrence #62. Commit afb5ecc changed Remove but not IndexOf. Not a duplicate of an open issue, and no open PR covers it.

    Generated by Claude Code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

bug

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions