Skip to content

Make IndexOf return the element Remove removes [patch] - #117

Merged
matt-edmondson merged 1 commit into
mainfrom
fix/107-indexof-matches-remove
Oct 14, 2026
Merged

matt-edmondson merged 1 commit into
mainfrom
fix/107-indexof-matches-remove

Conversation

@matt-edmondson

Copy link
Copy Markdown
Contributor

Fixes #107

What changed

OrderedCollection<T>.IndexOf and Remove now share a private FindMatchIndex helper. Among the run of elements that compare equal to the argument, it returns the first one that also Equals it. If none does, it falls back to the first element that compares equal.

Before this change, with a key-based comparer and duplicate keys, IndexOf(b) returned the index of a different element a that had the same key. RemoveAt(IndexOf(b)) then removed a and left b in the collection. Remove(b) already picked the right element.

Because of the fallback, Contains(x) being true still means IndexOf(x) >= 0.

Tests

  • IndexOf_KeyComparerWithDuplicateKeys_ReturnsIndexOfTheElementPassedIn
  • IndexOf_KeyComparerWithNoExactMatch_ReturnsFirstOccurrence
  • RemoveAtIndexOf_KeyComparerWithDuplicateKeys_RemovesSameElementAsRemove

I reverted the source change and reran the tests: the first and third fail without the fix and pass with it. The full suite passes locally (483 tests).

🤖 Generated with Claude Code

https://claude.ai/code/session_01SWgHqHW7R9hBKkZ6Zzx5Lg


Generated by Claude Code

With a key-based comparer and duplicate keys, IndexOf returned the first
element that merely compared equal, while Remove picked the one that also
Equals the argument. RemoveAt(IndexOf(x)) therefore removed a different
element than Remove(x). Both now share FindMatchIndex, which keeps the
fall-back to the first compare-equal element so Contains(x) still implies
IndexOf(x) >= 0.

Fixes #107

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SWgHqHW7R9hBKkZ6Zzx5Lg
@sonarqubecloud

Copy link
Copy Markdown

@matt-edmondson
matt-edmondson merged commit 9bbc5f4 into main Oct 14, 2026
14 checks passed
@matt-edmondson
matt-edmondson deleted the fix/107-indexof-matches-remove branch October 14, 2026 04:10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

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

2 participants