Skip to content

ReplaceWith empties the collection when the new items are derived from the collection itself #132

Description

@matt-edmondson

What's wrong

CollectionExtensions.ReplaceWith (Extensions/CollectionExtensions.cs, ~line 65) clears the collection before reading newItems. When newItems is a lazy query over the same collection, or the collection itself, it is read after the clear and yields nothing.

Repro

var list = new List<int> { 1, 2, 3, 4 };
list.ReplaceWith(list.Where(x => x > 2));
// list is [] — expected [3, 4]

var list2 = new List<int> { 1, 2, 3 };
list2.ReplaceWith(list2);
// list2 is [] — expected [1, 2, 3]

Reproduced against the current main build.

Why it matters

"Replace the contents with a filtered, sorted or projected version of themselves" (items.ReplaceWith(items.Where(...)), items.ReplaceWith(items.OrderBy(...))) is the most natural use of this helper, for example on an ObservableCollection bound to a UI where the instance must be kept. It silently wipes the data with no exception.

Suggested fix

Materialize the new items before clearing:

T[] snapshot = [.. newItems];
collection.Clear();
foreach (T item in snapshot) collection.Add(item);

Acceptance criteria

  • Both repro cases produce the expected contents.
  • Regression tests for a lazy self-query and for self-replacement.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions