Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added TryRemove to ConcurrentObservableDictionary and added unit test… #26

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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