Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does ObservableCollection<T>.Move(int,int) work?

People also ask

Why do we use ObservableCollection in C#?

An ObservableCollection is a dynamic collection of objects of a given type. Objects can be added, removed or be updated with an automatic notification of actions. When an object is added to or removed from an observable collection, the UI is automatically updated.

What is the difference between ObservableCollection and list?

The true difference is rather straightforward:ObservableCollection implements INotifyCollectionChanged which provides notification when the collection is changed (you guessed ^^) It allows the binding engine to update the UI when the ObservableCollection is updated. However, BindingList implements IBindingList.

What is ObservableCollection in xamarin forms?

If you want the ListView to automatically update as items are added, removed and changed in the underlying list, you'll need to use an ObservableCollection . ObservableCollection is defined in System.Collections.ObjectModel and is just like List , except that it can notify ListView of any changes: C# Copy.

How do you cast IEnumerable to ObservableCollection?

var myObservableCollection = new ObservableCollection<YourType>(myIEnumerable); This will make a shallow copy of the current IEnumerable and turn it in to a ObservableCollection.


Let me explain the behavior of Move in a form of a unit test:

[Test]
public void ObservableTest()
{
    var observable = new ObservableCollection<string> { "A", "B", "C", "D", "E" }; 

    observable.Move(1, 3); // oldIndex < newIndex 
    // Move "B" to "D"'s place: "C" and "D" are shifted left
    CollectionAssert.AreEqual(new[] { "A", "C", "D", "B", "E" }, observable);

    observable.Move(3, 1); // oldIndex > newIndex 
    // Move "B" to "C"'s place: "C" and "D" are shifted right
    CollectionAssert.AreEqual(new[] { "A", "B", "C", "D", "E" }, observable);

    observable.Move(1, 1); // oldIndex = newIndex
    // Move "B" to "B"'s place: "nothing" happens
    CollectionAssert.AreEqual(new[] { "A", "B", "C", "D", "E" }, observable);
}

I would go for the simple explanation:

The object is moved to the position indicated, and then all objects in collection are re-indexed from zero and up.