From 935dae7b6971651f8372af81a0a8ab07c40a7bfe Mon Sep 17 00:00:00 2001 From: John Stewien Date: Thu, 20 Oct 2022 15:39:14 +1030 Subject: [PATCH] Added TryRemove to ConcurrentObservableDictionary and added unit test. closes #25 --- .../ConcurrentObservableDictionaryTests.cs | 20 ++++++++++++++ .../ConcurrentObservableDictionary.cs | 26 +++++++++++++++++++ 2 files changed, 46 insertions(+) diff --git a/ExamplesAndTests/Swordfish.NET.UnitTestV3/ConcurrentObservableDictionaryTests.cs b/ExamplesAndTests/Swordfish.NET.UnitTestV3/ConcurrentObservableDictionaryTests.cs index b0187ff..c057e35 100644 --- a/ExamplesAndTests/Swordfish.NET.UnitTestV3/ConcurrentObservableDictionaryTests.cs +++ b/ExamplesAndTests/Swordfish.NET.UnitTestV3/ConcurrentObservableDictionaryTests.cs @@ -101,6 +101,26 @@ public void AddTest() Assert.IsTrue(allItemsPresent, "All items present"); } + [TestMethod] + public void TestTryRemove() + { + var testCollection = new ConcurrentObservableDictionary(); + for (int i = 0; i < 10; i++) + { + testCollection.Add($"Key{i}", $"Value{i}"); + } + Assert.AreEqual(10, testCollection.Count); + Assert.IsFalse(testCollection.TryRemove("Key10", out var value)); + for (int i = 9; i >= 0; i--) + { + string key = $"Key{i}"; + string expectedValue = $"Value{i}"; + Assert.IsTrue(testCollection.TryRemove(key, out var item)); + Assert.AreEqual(expectedValue, item); + Assert.AreEqual(i, testCollection.Count); + } + } + [TestMethod] public void TestManyOperations() { diff --git a/Swordfish.NET.CollectionsV3/ConcurrentObservableDictionary.cs b/Swordfish.NET.CollectionsV3/ConcurrentObservableDictionary.cs index 092ff92..c405122 100644 --- a/Swordfish.NET.CollectionsV3/ConcurrentObservableDictionary.cs +++ b/Swordfish.NET.CollectionsV3/ConcurrentObservableDictionary.cs @@ -182,6 +182,32 @@ public virtual KeyValuePair RemoveAt(int index) return localRemovedItem; } + public bool TryRemove(TKey key, out TValue item) + { + var outputItemAndIndex = DoReadWriteNotify( + // Get the list of keys and values from the internal list + () => _internalCollection.GetItemAndIndex(key), + // remove the keys from the dictionary, remove the range from the list + (itemAndIndex) => _internalCollection.Remove(key), + // Notify which items were removed + (itemAndIndex) => itemAndIndex != null ? new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, itemAndIndex.Item, itemAndIndex.Index) : null + ); + + // If the return container which holds the item and its index + // is not null then asign the item and return true, else + // return false. + if (outputItemAndIndex != null) + { + item = outputItemAndIndex.Item.Value; + return true; + } + else + { + item = default(TValue); + return false; + } + } + public bool Remove(TKey key) { var retVal = DoReadWriteNotify(