views:

171

answers:

2

In a non-Silverlight world, it is easy to use LINQ to create an ObservableCollection. This is because the ObservableCollection class has constructors that accept any IEnumerable<T> or List<T>. However, the Silverlight version does not! This means that code such as:

var list = (from item in e.Result
            select new ViewModel(item)).ToList();

Items = new System.Collections.ObjectModel.ObservableCollection<ViewModel>(list);

will not work in Silverlight.

Is there another option to make this work besides resorting to a for-each statement?

+1  A: 

Well That works if you are using Silverlight 4. try this:

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

found in: http://forums.silverlight.net/forums/p/39487/262505.aspx

Gabriel Guimarães
I didn't know this deficiency has already been addressed in SL4, thanks!
SonOfPirate
@sonofpirate: In fact in SL4 you can drop the ToList since there is an constructor on `ObservableCollection<T>` that takes `IEnumerable<T>`.
AnthonyWJones
Excellent! I can't wait until we get the green light to upgrade to SL4!
SonOfPirate
+5  A: 

I dont think so, but you can make it cleaner using this extension method.

 public static ObservableCollection<T> ToObservableCollection<T>(this IEnumerable<T> coll) {
        var c = new ObservableCollection<T>();
        foreach (var e in coll)
            c.Add(e);
        return c;
    }
alejandrobog
Barring another option, this was the approach I was going to use. I was just hoping there was another, more graceful way to get it done.
SonOfPirate
@sonofpirate: In SL3 this is very good way, even in SL4 I might be inclined to create this extension method anyway (although using the correct constructor in the implementation).
AnthonyWJones