Skip to content

Commit

Permalink
Merge pull request #26 from stewienj/25-concurrentobservabledictionar…
Browse files Browse the repository at this point in the history
…y-doesnt-implement-tryremove

Added TryRemove to ConcurrentObservableDictionary and added unit test…
  • Loading branch information
stewienj authored Oct 20, 2022
2 parents e0d7c7d + 935dae7 commit 31bfbd5
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,26 @@ public void AddTest()
Assert.IsTrue(allItemsPresent, "All items present");
}

[TestMethod]
public void TestTryRemove()
{
var testCollection = new ConcurrentObservableDictionary<string, string>();
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()
{
Expand Down
26 changes: 26 additions & 0 deletions Swordfish.NET.CollectionsV3/ConcurrentObservableDictionary.cs
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,32 @@ public virtual KeyValuePair<TKey, TValue> 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(
Expand Down

0 comments on commit 31bfbd5

Please sign in to comment.