Convert a List<T> into an ObservableCollection<T>

C#Windows Runtime

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

ObservableCollection < T > has a constructor [overload][1] [1]: http://msdn.microsoft.com/en-us/library/cc679169.aspx 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>);

Solution 2 - C#

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

 public ObservableCollection(
      List<T> list
 )

Solution 3 - C#

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);
    }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionraghu_3View Question on Stackoverflow
Solution 1 - C#DenisView Answer on Stackoverflow
Solution 2 - C#Piotr StappView Answer on Stackoverflow
Solution 3 - C#PaulCView Answer on Stackoverflow