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); } }