Repository navigation
Description
Update 10/04/2018
@ianhays and I discussed this and we agree to add this 6 APIs for now:
// Adds a range to the end of the collection.
// Raises CollectionChanged (NotifyCollectionChangedAction.Add)
public void AddRange(IEnumerable<T> collection) => InsertItemsRange(0, collection);
// Inserts a range
// Raises CollectionChanged (NotifyCollectionChangedAction.Add)
public void InsertRange(int index, IEnumerable<T> collection) => InsertItemsRange(index, collection);
// Removes a range.
// Raises CollectionChanged (NotifyCollectionChangedAction.Remove)
public void RemoveRange(int index, int count) => RemoveItemsRange(index, count);
// Will allow to replace a range with fewer, equal, or more items.
// Raises CollectionChanged (NotifyCollectionChangedAction.Replace)
public void ReplaceRange(int index, int count, IEnumerable<T> collection)
{
RemoveItemsRange(index, count);
InsertItemsRange(index, collection);
}
#region virtual methods
protected virtual void InsertItemsRange(int index, IEnumerable<T> collection);
protected virtual void RemoveItemsRange(int index, int count);
#endregionAs those are the most commonly used across collection types and the Predicate ones can be achieved through Linq and seem like edge cases.
To answer @terrajobst questions:
Should the methods be virtual? If no, why not? If yes, how does eventing work and how do derived types work?
Yes, we would like to introduce 2 protected virtual methods to stick with the current pattern that we follow with other Insert/Remove apis to give people hability to add their custom removals (like filtering items on a certain condition).
Should some of these methods be pushed down to Collection?
Yes, and then ObservableCollection could just call the base implementation and then trigger the necessary events.
Let's keep the final speclet at the top for easier search
Speclet (Updated 9/23/2016)
Scope
Modernize Collection<T> and ObservableCollection<T> by allowing them to handle operations against multiple items simultaneously.
Rationale
The ObservableCollection is a critical collection when it comes to XAML-based development, though it can also be useful when building API client libraries as well. Because it implements INotifyPropertyChanged and INotifyCollectionChanged, nearly every XAML app in existence uses some form of this collection to bind a set of objects against UI.
However, this class has some shortcomings. Namely, it cannot currently handle adding or removing multiple objects in a single call. Because of that, it also cannot manipulate the collection in such a way that the PropertyChanged events are raised at the very end of the operation.
Consider the following situation:
- You have a XAML app that accesses an API.
- That API call returns 25 objects that need to be bound to the UI.
- In order to get the data displayed into the UI, you likely have to cycle through the results, and add them one at a time to the ObservableCollection.
- This has the side-effect of firing the
CollectionChangedevent 25 times. If you are also using that event to do other processing on incoming items, then those events are firing 25 times too. This can get very expensive, very quickly. - Additionally, that event will have
ChangedItemsLists that will only ever have 0 or 1 objects in them. That is... not ideal.
This behavior is unnecessary, especially considering that NotifyCollectionChangedEventArgs already has the components necessary to handle firing the event once for multiple items, but that capability is presently not being used at all.
Implementing this properly would allow for better performance in these types of apps, and would negate the need for the plethora of replacements out there (here, here, and here, for example).
Usage
Given the above scenario as an example, usage would look like this pseudocode:
var observable = new ObservableCollection<SomeObject>();
var client = new HttpClient();
var result = client.GetStringAsync("http://someapi.com/someobject");
var results = JsonConvert.DeserializeObject<SomeObject>(result);
observable.AddRange(results);Implementation
This is not the complete implementation, because other *Range functionality would need to be implemented as well. You can see the start of this work in PR dotnet/corefx#10751
// Adds a range to the end of the collection.
// Raises CollectionChanged (NotifyCollectionChangedAction.Add)
public void AddRange(IEnumerable<T> collection)
// Inserts a range
// Raises CollectionChanged (NotifyCollectionChangedAction.Add)
public void InsertRange(int index, IEnumerable<T> collection);
// Removes a range.
// Raises CollectionChanged (NotifyCollectionChangedAction.Remove)
public void RemoveRange(int index, int count);
// Will allow to replace a range with fewer, equal, or more items.
// Raises CollectionChanged (NotifyCollectionChangedAction.Replace)
public void ReplaceRange(int index, int count, IEnumerable<T> collection);
// Removes any item that matches the search criteria.
// Raises CollectionChanged (NotifyCollectionChangedAction.Remove)
// RWM: Excluded for now, will see if possible to add back in after implementation and testing.
// public int RemoveAll(Predicate<T> match);Obstacles
Doing this properly, and having the methods intuitively named, could potentially have the side effect of breaking existing classes that inherit from ObservableCollection to solve this problem. A good way to test this would be to make the change, compile something like Template10 against this new assembly, and see if it breaks.
So the ObservableCollection is one of the cornerstones of software development, not just in Windows, but on the web. One issue that comes up constantly is that, while the OnCollectionChanged event has a structure and constructors that support signaling the change for multiple items being added, the ObservableCollection does not have a method to support this.
If you look at the web as an example, Knockout has a way to be able to add multiple items to the collection, but not signal the change until the very end. The ObservableCollection needs the same functionality, but does not have it.
If you look at other extension methods to solve this problem, like the one in Template10, they let you add multiple items, but do not solve the signaling problem. That's because the ObservableCollection.InsertItem() method overrides Collection.InsertItem(), and all of the other methods are private. So the only way to fix this properly is in the ObservableCollection itself.
I'm proposing an "AddRange" function that accepts an existing collection as input, optionally clears the collection before adding, and then throws the OnCollectionChanging event AFTER all the objects have been added. I have already implemented this in a PR dotnet/corefx#10751 so you can see what the implementation would look like.
I look forward to your feedback. Thanks!
Activity
robertmclaws commentedon Sep 13, 2016
@joshfree @Priya91 Since I already have a PR that addresses this issue, is there any way this could be moved up to 1.1?
LanceMcCarthy commentedon Sep 13, 2016
While you're in there adding an AddRange() method, can you throw an OnPropertyChanged() into the Count property's setter? Thanks :)
thomaslevesque commentedon Sep 13, 2016
A long time ago I had implemented a
RangeObservableCollectionwithAddRange,RemoveRange,InsertRange,ReplaceRangeandRemoveAll. But it turned out that the WPF binding system didn't supportCollectionChangednotifications with multiple items (I seem to remember it has been fixed since then, but I'm not sure).joshfree commentedon Sep 13, 2016
@Priya91 can you help shepherd this through the API review process http://aka.ms/apireview with @robertmclaws ?
/cc @terrajobst
Priya91 commentedon Sep 13, 2016
Sure.
Priya91 commentedon Sep 13, 2016
@robertmclaws Can you create an api speclet on this issue, outling the api syntax, like this. Mainly interested in usage scenarios
svick commentedon Sep 14, 2016
@robertmclaws
In what situation could it be a breaking change? The only issue I can think of is that it would cause a warning that tells you to use
newif you meant to hide a base class member, which would be actually an error with warnings as errors enabled. Is this what you meant? Or is there another case I'm missing?robertmclaws commentedon Sep 14, 2016
@svick Could possibly be a runtime problem. If you just upgraded the framework w/o recompiling, I'm not sure exactly how the runtime execution would react. We'd need to test it just to make sure.
svick commentedon Sep 14, 2016
@robertmclaws I think that could only be a problem if you don't recompile, but you do upgrade a library with the custom type inheriting from
ObservableCollection<T>, which removed its version ofAddRange()in the new version. But that would be the fault of that library.Otherwise, adding a new member won't affect how old binaries behave.
Priya91 commentedon Sep 14, 2016
+1 The api sounds good to me. For manipulating multiple items , along with AddRange, does it provide value to add, InsertRange, RemoveRange, GetRange for the specified usage scenarios?
cc @terrajobst
robertmclaws commentedon Sep 16, 2016
@svick You are probably right. I personally would want to test the behavior just to be sure we're not breaking anyone... otherwise this would move to a 2.0 release item.
@Priya91 I'm not sure if a
GetRange()would be necessary, butInsertRange()andRemoveRange()would be, along withReplaceRange(), and possible aClear()method if one is not currently available.So if we're comfortable with the API, what's the next step? :)
Priya91 commentedon Sep 16, 2016
Clear is already available. We still haven't gotten the shape of apis to add, if RemoveRange and InsertRange are to be added, then we need these apis added to the speclet. And then we'll mark api-ready-for-review, to be discussed in the next api-review meeting either on tuesday or friday.
robertmclaws commentedon Sep 16, 2016
OK, I made changes to the speclet. Note that the parameters might change for the actual implementation, but those are what makes the most sense at this particular second. Please LMK if I need to do anything else. Thanks!
Priya91 commentedon Sep 16, 2016
RemoveRange(int index, int count)instead ofRemoveRange(ICollection)? How does RemoveRange behave when the ICollection elements are duplicated in ObservableCollection463 remaining items
cyraid commentedon Feb 27, 2026
I'm working with Avalonia, and I've had to implement supporting the items in the add / remove / etc events, knowing that only one control is being add/removed at a time as there's no AddRange? ... Why put us through the torture? Why wouldn't you have just had 'single item' instead of a list in the changed event? Sigh .. More gatekeeping and red tape.
Edit: I know! I'll let the collection be replaced by a new one, and I'll just copy all the listeners over to the new one and ....... Can't do that either..
Insire commentedon Feb 27, 2026
Avalonia solved this with their own implementation of INotifyCollectionChanged which does have range support, as can be found here
cyraid commentedon Feb 27, 2026
@Insire It was more tongue and cheek, because I'm using an API that uses ObservableCollection and not Avalonia (separate project) but the editor uses that, and hooks it up to the avalonia side. So I can't use a different class. If it were all Avalonia, yeah, I would've definitely went to AvaloniaList. Not sure why MS couldn't add in a different class then that is identical to ObservableCollection, duplicate all that code, and add AddRange.
Add bulk collection operation extensions for Collection<T> and Observ…
robertmclaws commentedon Mar 4, 2026
Hey folks!
Sorry it has been much later than I said it would, but I've finally shipped EasyAF.Extensions.Collections, a stand-alone NuGet package with no dependencies that leverages .NET 10 extension classes to enhance both
Collection<T>andObservableCollection<T>with Range methods virtually identical to #65101.ObservableCollection<T>uses the new batching behavior by default. if you include this in your code, the assumption is you WANT batching by default. However, you can opt-into the WPF-era behavior by passing inCollectionChangeNotificationMode.Reset.It uses
[OverloadResolutionPriority(1)]to make sure it is called before other extensions / subclasses, and it uses UnsafeAccessors instead of Reflection to make it AOT compliant, so your Blazor, MAUI, BlazorEssentials, and Uno apps can benefit from EVEN BETTER performance.You can check out the source here and get the documentation for
Collection<T>here andObservableCollection<T>here.If you have any issues, please open them here: https://github.com/CloudNimble/EasyAF/issues. This is a preview release, but is thoroughly tested, and will be shipping with EasyAF 4.0.2 in a few days.
(BTW, if you like the documentation [be gentle, EasyAF's docs are a work in progress], check out https://dotnetdocs.com, it's a side project of mine to help make .NET documentation amazing again.)
dotMorten commentedon Mar 4, 2026
Nice work @robertmclaws, but hopefully this work won't be the excuse to not get this issue resolved.
robertmclaws commentedon Mar 4, 2026
Thanks, @dotMorten! Coming from you that's high praise.
Actually, I'm hoping my implementation forces them to fix the ecosystem, and here's why:Using OverloadResolutionPriority(1) means that my code will always take first position in overload resolution.That means any subclass of ObservableCollection will now be using this behavior, which intentionally breaks WPF by default.I need to add more unit tests to confirm this behavior,but if enough of you adopt this and get vocal about it on socials, we can force the WPF team to fix their broken code (that never should have passed code review in the first place... having lived through the Longhorn era the performance degradation it causes is probably a significant contribution to why they had to pull WPF out of the OS).jnm2 commentedon Mar 4, 2026
@robertmclaws OverloadResolutionPriority only breaks ties between methods in the same declaring type. When placed on extension methods, it only breaks ties between extension methods declared in the same static class.
jnm2 commentedon Mar 4, 2026
Now, you could ship a Roslyn interceptor, which is a source generator which would actually replace calls with your own implementation: https://github.com/dotnet/roslyn/blob/main/docs/features/interceptors.md. It would fall foul of:
But it would work.
robertmclaws commentedon Mar 5, 2026
@jnm2 Thanks for all that info! I'm disappointed that the extension + overload priority doesn't work across classes, however if there was enough interest and a use case I could definitely add a Roslyn Generator for interception.
LWChris commentedon Mar 12, 2026
This sounds as good and as bad as a self-merging pull-request for this issue. Something gets done, albeit the completely wrong way by violating all well-established conventions, but at least something gets done.
robertmclaws commentedon Mar 12, 2026
@LWChris The fun thing about putting things in a NuGet package is that you don't have to use it if you don't want to.
LWChris commentedon Mar 13, 2026
@robertmclaws Yes. I was referring to that your code has to inject itself with "sledgehammer and prybar" in order to get things done, which is as funny as it is sad. But I'm glad things are slowly moving now.
Release 4.1.0 (#2)
feat: add a range-capable appointments collection