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,237
  • 1
  • 28
  • 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
  • 16,268
  • 4
  • 64
  • 88
5

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

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

this works for me:

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

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

Piotr Justyna
  • 4,888
  • 3
  • 25
  • 40