Is there any way to initialize the capacity of an ObservableCollection<T> like you can a List<T>?

For example:

var observableCollection = new ObservableCollection<int>(100);
有帮助吗?

解决方案

No there is not. One of the constructors for ObservableCollection<T> takes a List<T>, so you might think you can do this:

new ObservableCollection<int>(new List<int>(100));

But that doesn't work. Internally, ObservableCollection copies the list and doesn't take into account any capacity properties on the list. You can verify this by looking at the constructors using .NET Reflector.

其他提示

This is an old question. But, I thought it might be worthwhile to know that currently, it is possible to set the backing List capacity at the risk of relying on the internal implementation.

The Items property that is exposed by the base Collection<T> class is currently implemented as a List<T>. With type casting, you can set that property's Capacity.

Note that this does rely on the current implementation of both the List<T> and ObservableCollection<T> classes. If it is critical that you be able to set the backing Capacity and not worry that the .NET implementation will change (for instance, changing the backing list to a Dictionary or HashSet), you should instead create a new class that implements your needed interfaces.

You can use the Microsoft Reference Source as well as .NET Reflector.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top