Pages

Saturday, September 7, 2013

Convert List to a ObservableCollection

Observable Collections are heavily used in Silverlight, WPF Applications instead of Lists. Observable Collection works essentially like a regular collection but it implements INotifyCollectionChanged and INotifyPropertyChanged interfaces. Because of that you can get to know when Collection is changed. ObservableCollection are optimized for databinding  purposes.

Sometimes you will need to convert your list to an ObservableCollection. This Extension method enables that. 

public static class CollectionExtensions
{
        public static ObservableCollection ToObservableCollection(this IEnumerable coll)
        {
            var c = new ObservableCollection();
            foreach (var e in coll)
                c.Add(e);
            return c;
        }
 }