146

I have a List<T> which is being populated from JSON. I need to convert it into an ObservableCollection<T> to bind it to my GridView.

Any suggestions?

reuben
  • 3,360
  • 23
  • 28
raghu_3
  • 1,849
  • 3
  • 18
  • 29
  • Duplicate - http://stackoverflow.com/questions/9069445/the-best-way-to-convert-listobject-to-observablecollectionobject/41731406#41731406 – vapcguy Jan 18 '17 at 23:53
  • It is duplicate but its a bit too late since this question amounted way more attention. and you linking for your own answer seems rather low. IMO your answer expands unnecessarily out of the focus of the question. if the OP has `List` no matter how many levels it has, it can do `ObservableCollection xxx = new(listT);` – Barreto May 13 '23 at 13:26

3 Answers3

309

ObservableCollection < T > has a constructor overload which takes IEnumerable < T >

Example for a List of int:

ObservableCollection<int> myCollection = new ObservableCollection<int>(myList);

One more example for a List of ObjectA:

ObservableCollection<ObjectA> myCollection = new ObservableCollection<ObjectA>(myList as List<ObjectA>);
Casper
  • 4,435
  • 10
  • 41
  • 72
Denis
  • 5,894
  • 3
  • 17
  • 23
19

ObervableCollection have constructor in which you can pass your list. Quoting MSDN:

 public ObservableCollection(
      List<T> list
 )
Piotr Stapp
  • 19,392
  • 11
  • 68
  • 116
7

The Observable Collection constructor will take an IList or an IEnumerable.

If you find that you are going to do this a lot you can make a simple extension method:

    public static ObservableCollection<T> ToObservableCollection<T>(this IEnumerable<T> enumerable)
    {
        return new ObservableCollection<T>(enumerable);
    }
PaulC
  • 101
  • 1
  • 3