Does ObservableCollection support insertion order?

I was wondering if the ObservableCollection is guaranteed to maintain the order of the elements inserted into it in C #. I looked at the MSDN website but could not find the answer.

+4
source share
3 answers

It is derived from Collection<T> , which uses IList<T> items to store data. For example, when adding and removing elements, the ObservableCollection simply delegates the call to the base class.

 protected override void InsertItem(int index, T item) { this.CheckReentrancy(); base.InsertItem(index, item); this.OnPropertyChanged("Count"); this.OnPropertyChanged("Item[]"); this.OnCollectionChanged(NotifyCollectionChangedAction.Add, (object) item, index); } 

Collection in C # in an ordered data structure, so the relative order of elements after insertion and deletion should not be changed.

+2
source

Yes.

ObservableCollection<T> implements IList<T> , which means that the elements are stored in the order you specify.


Typically, this is how basic collection types work in .NET.

IEnumerable<T> allows you to access elements one at a time in an unspecified order.

ICollection<T> allows you to add and remove elements and access the total size of the collection in addition to the capabilities of IEnumerable<T> .

IList<T> allows you to access elements by index, as well as insert and delete elements with arbitrary indexes in addition to the ICollection<T> capabilities.

+9
source

Please see excerpts from the ObservableCollection Class MSDN documentation :

Methods:

 Add Adds an object to the *end* of the Collection<T>. (Inherited from Collection<T>.) Insert Inserts an element into the Collection<T> at the *specified index*. (Inherited from Collection<T>.) InsertItem Inserts an item into the collection at the *specified index*. (Overrides Collection<T>.InsertItem(Int32, T).) 

Explicit interface implementation:

 IList.Add Adds an item to the IList. (Inherited from Collection<T>.) IList.Insert Inserts an item into the IList at the specified index. (Inherited from Collection<T>.) 
+2
source

Source: https://habr.com/ru/post/1482177/


All Articles