How to cast a List<T> to an ObservableCollection<T> in Silverlight
I am in Silverlight, and have a generic list: List<T>.
Now I wish to cast it to a generic observable collections: ObservableCollection<T>.
I understand I can iterate over the list and add each individual item to the Observable collection.
However, it seems to me there has to be a built-in way of doing this.
Does anyone know?
Jacob Tanner, Jul 22, 2010
I am also working in a silverlight application and had issues while converting List<T> to ObservableCollection.
I found solution to this by way of Extension method. The code is as follows:
Once the above code is added, you can just call List<T>.ToObservableCollection() which will convert your List<T> to observable collection.
I hope this helps.
Harshad Riswadkar, Sep 16, 2010
I am not developing in Silverlight, but I believe that there is no ctor in silverlight that accepts a List<T>. What you can do to make things easier and reusable is implementing an extension method.
Head over here and here to get an idea.
Christian Jacob, Aug 20, 2010
Have you tried using the constructor from the ObservableCollection<T>? There’s a constructor that accepts a List<T>.
I’m not sure if you’re aware of this, but you can use .Net Reflector (a freeware app) to disassemble the framework in order to see what’s available inside the class. I’ll post some code that I pulled from the 4.0 framework below including the constructor. As you can see there’s a method in the ObservableCollection<T> called CopyFrom which populates an items collection in the ObservableCollection<T> base class. Unfortunately the class signatures are different so they're not exactly interchangeable...
Andrew Green, Jul 28, 2010