2

I know I can create a List<T> from IEnumerable<T> by doing
myEnumerableCollection.ToList(), but how could I implement the same thing for an ObservableCollection<T> ?

Jake Berger
  • 5,027
  • 1
  • 27
  • 22
MaesterZ
  • 72
  • 1
  • 9

4 Answers4

9

What you're looking for is extension methods.

You can extend the IEnumerable<T> type like this:

namespace myNameSpace
{
    public static class LinqExtensions
    {
       public static ObservableCollection<T> ToObservableCollection<T>(this IEnumerable<T> _LinqResult)
       {
          return new ObservableCollection<T>(_LinqResult);              
       }
    }
}

Don't forget to add the using directive in classes you want to use this in (i.e: using myNameSpace;)

Louis Kottmann
  • 15,672
  • 4
  • 60
  • 85
5

Why would you need to cast it? That's syntactic sugar for common operations.

var observableCollection = new ObservableCollection<object>(regularCollection);
Trevor Elliott
  • 11,062
  • 11
  • 56
  • 102
1

this works for me:

 List<string> ll = new List<string> { "a", "b","c" };
 ObservableCollection<string> oc = new ObservableCollection<string>(ll);
Yoav
  • 3,286
  • 3
  • 32
  • 69
0

You have to create new ObservableCollection instance populated with your collection (IEnumerable).

Piotr Justyna
  • 4,622
  • 3
  • 23
  • 40