Convert a List into an ObservableCollection

前端 未结 3 1002
终归单人心
终归单人心 2021-01-31 00:40

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

相关标签:
3条回答
  • 2021-01-31 01:26

    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);
        }
    
    0 讨论(0)
  • 2021-01-31 01:34

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

     public ObservableCollection(
          List<T> list
     )
    
    0 讨论(0)
  • 2021-01-31 01:39

    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>);
    
    0 讨论(0)
提交回复
热议问题