Why ObservableCollection
doesn't has the RemoveAll
method like a List
?
I have implemented an extension method to provide this functionality to the ObservableCollection
, but I would like to understand if there is a specific reason for not providing this functionality.
Would it possibly effect Data Binding in some way due to Collection change? This post does specify a few things that could go wrong while using ObservableCollections
, but does not address this question.
It does have a Clear()
method that removes all items that you can use instead.
If I had to hazard a guess as to why they used Clear
instead of RemoveAll
, I think it would be because RemoveAll
carries the suggestion that you are removing items from the collection, while Clear
tells you the items are simply being cleared.
This makes a difference in the type of CollectionChanged
notification that gets raised. Clear()
raises a NotifyCollectionChangedAction.Reset
event and does not include the removed items in the event, while Remove
raises a NotifyCollectionChangedAction.Removed
event, and passes the removed item to the event.
You cannot raise a CollectionChanged
event with multiple items, so raising a NotifyCollectionChangedAction.Removed
event with all the items removed would throw an exception. The alternative would be to raise a CollectionChanged
event for every item that got removed, which can be quite bad for performance. And simply raising a NotifyCollectionChangedAction.Reset
event would cause some confusion when users are expecting a Removed
event to occur when they are removing items.
So I am guessing they decided to simply use .Clear()
instead of .RemoveAll()
because the name is a better description of what is actually happening behind the scenes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With