IEnumerable.ToObservableCollection

In WPF/Silverlight, binding UI objects such as DataGrid or ListBox to collections is typically done using an ObservableCollection instead of the generic List object. This way, our UI is automatically synchronized since the observable collection provides event notification to WPF data binding engine whenever items are added, removed, or when the whole list is refreshed. The LINQ extension methods that return a collection actually return IEnumerable<T>. The .NET framework for Silverlight provides built-in extension methods to convert IEnumerable<T> to List<T> and Array<T> but there’s no method available to convert the collection to ObservableCollection<T>(WPF developers can simply use this constructor overload) . So here’s one you may find useful:

public static class CollectionExtensions
{
    public static ObservableCollection<T> ToObservableCollection<T>(this IEnumerable<T> enumerableList)
    {
        if (enumerableList != null)
        {
            //create an emtpy observable collection object
            var observableCollection = new ObservableCollection<T>();

            //loop through all the records and add to observable collection object
            foreach (var item in enumerableList)
                observableCollection.Add(item);

            //return the populated observable collection
            return observableCollection;
        }
        return null;
    }
}

Extension methods are very powerful and I am planning to post an example demonstrating their potential.

Advertisements

19 Responses to “IEnumerable.ToObservableCollection”

  1. Chris Says:

    Do you have any follow up examples of this? I’ve been trying to get something like this to work for a few days and I’m not having much luck.

    thanks!

  2. Jann Says:

    The ObservableCollection actually has a constructor that takes an IEnumerable. It would be better to use the constructor because every call to Add(item) causes the CollectionChanged event to fire, which means more overhead.

  3. Syed Mehroz Alam Says:

    @Chris
    I followed this post with an introduction to creating and using Extension Methods here. Hope that helps in clarifying concepts.

    @Jann
    Unfortunately, that constructor is only available for WPF programmers (msdn link here ) and there’s no such facility for Silverlight developers (msdn link here). I should have explicitly said this in my post; will do it soon. Thanks for pointing out.

  4. haveaproblem Says:

    I have an error on “foreach (var item in enumerableList)”:
    “Only a single enumeration is supported by this IEnumerable.”

    Can’t figure out, what’s the problem 😦 ??

  5. haveaproblem Says:

    I’m using it in Silverlight App (3.0)

  6. Syed Mehroz Alam Says:

    @haveaproblem

    Haven’t ran into it anytime. Can you share the code how you are using it?

  7. Raj Says:

    if I load related entities using .Expand(“”) in the query then I get “Only a single enumeration is supported by this IEnumerable” error.
    var qry =
    from p in TheContext.Products.Expand(“Supplier”).Expand(“Category”)
    orderby p.ProductName
    select p;

    The below line throws exception:
    List products = productQuery.EndExecute(result).ToList();

  8. Raj Says:

    In the above code, I had foreach (var item in enumerableList) code before using the .ToList() fn., after removing the foreach code, .ToList() works fine. Also, I noticed that you can only enumerate foreach (var item in enumerableList) once, if you repeat foreach(…) code one more time, you get this error. So, it is a best to convert it to List and use it.

  9. Syed Mehroz Alam Says:

    @Raj

    I also found this thread in Silverlight forums. Looks like ADO.NET data services aren’t happy with enumerables in Silverlight 3 RTM.

  10. Fred Mastro Says:

    I’ve posted a VB.NET version of the code on my blog here, http://www.fredmastro.com/post/Sending-GenericList-collection-back-to-WCF-ObservableCollection.aspx

    I posted a copy of the article and referenced this page as the source. If you wish me to remove the article, let me know. Thank you.

  11. Rodney Says:

    Awesome – thanks for sharing – I am on SL4 and using LINQ on an XML file and then binding to it – perfect!

  12. Frank Says:

    Is there any way to use ria .. load data into an observable collection, and then have that observable collection accessed by multiple datagrids on different pages or child windows throughout a solution?

  13. vingador Says:
    public static class CollectionExtensions {
        public static ObservableCollection<T> ToObservableCollection<T>(this IEnumerable<T> enumerableList) {
            if (enumerableList != null) {
                //create an observable collection object
                //you can pass the IEnumerable inside the ObservableCollection Constructor
                return new ObservableCollection<T>(enumerableList);
            }
            return null;
        }
    }
    
  14. Water Damage Restoration Says:

    This is the version that i have been using, works good… The add new item, delete & edit buttons were grayed out on my dataform and i spent hours trying to figure out what the problem was. I used the pagedcollectionview and the buttons were visible. v2_Customer is name of my table. The event below fires when the datagrid_selection_changed event fires.

    Dim taskList As ObservableCollection(Of v2_Customer) = New ObservableCollection(Of v2_Customer)
    ‘ Dim custID As Guid = (CType(V2_CustomerDataGrid.SelectedItem, _
    ‘ v2_Customer)).Cust_UUID
    ‘ Generate some task data and add it to the task list.
    For index = 1 To 14
    taskList.Add(New v2_Customer() With _
    {.Cust_UUID = custID, .Company_UUID, .City
    })
    Next

    Dim taskListView As New PagedCollectionView(taskList)
    Me.CustomerDataForm1.ItemsSource = taskListView

  15. memphis23 Says:

    I am afraid that UI is not automatically synchronized since the observable collection changes.

  16. Kaminomoto Says:

    I am really impressed with your writing skills and also with the
    layout on your blog. Is this a paid theme or did you customize
    it yourself? Either way keep up the nice quality writing,
    it is rare to see a great blog like this one these days.

  17. Pawn Star Married Says:

    What’s up, yes this piece of writing is truly good and I have learned lot of things from it regarding blogging. thanks.

  18. Extension method for casting IEnumerable to ObservableCollection | Zain Shaikh Says:

    […] my time in just figuring it out, why not to google, there may be some solution. and soon I found this website where the following class was provided, which simply easily helped me […]


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: