How to create an ObservableCollection using LINQ in Silverlight

In a world other than Silverlight, it's 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 work! This means that the code, for example:

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 way to make this work, besides resorting to a for-each statement?

+3
source share
2 answers

This works well if you are using Silverlight 4. try the following:

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 at: http://forums.silverlight.net/forums/p/39487/262505.aspx

+1

, , .

 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;
    }
+5

Source: https://habr.com/ru/post/1742304/


All Articles