From b2a00bf33df717da8041f824a1dcbc160b1501f4 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 26 Sep 2026 05:27:27 +0000 Subject: [PATCH] fix: read ReplaceWith's new items before clearing the collection [patch] ReplaceWith cleared the collection and then enumerated newItems, so a lazy query over the collection (items.Where(...)) or the collection itself yielded nothing and the collection ended up empty. Snapshot newItems into an array before clearing. Fixes ktsu-dev/Extensions#132 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012Hhb8knddbu4LRSs2uu9jR --- Extensions.Test/CollectionExtensionsTests.cs | 20 ++++++++++++++++++++ Extensions/CollectionExtensions.cs | 4 +++- 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/Extensions.Test/CollectionExtensionsTests.cs b/Extensions.Test/CollectionExtensionsTests.cs index 9fff389..38e3ba0 100644 --- a/Extensions.Test/CollectionExtensionsTests.cs +++ b/Extensions.Test/CollectionExtensionsTests.cs @@ -239,4 +239,24 @@ public void ReplaceWithNewItemsContainingNullsReplacesCorrectly() CollectionAssert.AreEqual(new List { "x", null, "z" }, collection); } + + [TestMethod] + public void ReplaceWithLazyQueryOverSameCollectionKeepsMatchingItems() + { + List collection = [1, 2, 3, 4]; + + collection.ReplaceWith(collection.Where(x => x > 2)); + + CollectionAssert.AreEqual(new List { 3, 4 }, collection); + } + + [TestMethod] + public void ReplaceWithSameCollectionKeepsItems() + { + List collection = [1, 2, 3]; + + collection.ReplaceWith(collection); + + CollectionAssert.AreEqual(new List { 1, 2, 3 }, collection); + } } diff --git a/Extensions/CollectionExtensions.cs b/Extensions/CollectionExtensions.cs index 4d65af0..295812d 100644 --- a/Extensions/CollectionExtensions.cs +++ b/Extensions/CollectionExtensions.cs @@ -62,7 +62,9 @@ public static void ReplaceWith(this ICollection oldItems, IEnumerable n } #pragma warning restore KTSU0004 // Use Ensure.NotNull instead of manual null check + // Materialize first: newItems may be the collection itself or a lazy query over it, which Clear would empty + T[] snapshot = [.. newItems]; oldItems.Clear(); - oldItems.AddFrom(newItems); + oldItems.AddFrom(snapshot); } }