How does one convert an ObservableCollection
to a List
of the held objects?
Given that ObservableCollection<T> implements IEnumerable<T> you can give it to the constructor of List<T> : List<T> myList = new List<T>(myObservableCollection); Where T is the type of the items in the collection.
You can directly change it to Observablecollection , just as follows: public static ObservableCollection<Model> list = new ObservableCollection<Model>() { new Model() { Text = "A" }, new Model() { Text = "B" }, new Model() { Text = "C" }, new Model() { Text = "D" } };
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.
var myObservableCollection = new ObservableCollection<YourType>(myIEnumerable); This will make a shallow copy of the current IEnumerable and turn it in to a ObservableCollection.
Just need to add the namespace using System.Linq;
and use the method ToList()
in the ObservableCollection object
Depending on the type of object in the ObservableCollection
... I'll assume it's an int
for this example:
IEnumerable<int> obsCollection = (IEnumerable<int>)GetCollection(); var list = new List<int>(obsCollection);
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