Back to list
Views:   40.1K
Replies:  3
Archived

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
Reply 1
Hi Jacob,

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:

public static class ObservableExtensions
    {
        public static ObservableCollection<T> ToObservableCollection<T>(this List<T> items)
        {
            ObservableCollection<T> collection = new ObservableCollection<T>();

            foreach (var item in items)
            {
                collection.Add(item);
            }

            return collection;
        }
    }

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
Reply 2
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.

-Chris.
Christian Jacob, Aug 20, 2010
Reply 3
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...



public class ObservableCollection<T> : Collection<T>, INotifyCollectionChanged, INotifyPropertyChanged   

public ObservableCollection(List<T> list) : base((list != null) ? new List<T>(list.Count) : list)   
{   
    this._monitor = new SimpleMonitor<T>();   
    this.CopyFrom(list);   
}   

public class List<T> : IList<T>, ICollection<T>, IEnumerable<T>, IList, ICollection, IEnumerable   


public class Collection<T> : IList<T>, ICollection<T>, IEnumerable<T>, IList, ICollection, IEnumerable   

 
Andrew Green, Jul 28, 2010


Stay Inspired!
Join other developers and designers who have already signed up for our mailing list.
Terms     Privacy     Licensing       EULA       Sitemap      
© Data & Object Factory, LLC.
Made with    in Austin, Texas