将List <T>转换为ObservableCollection <T>


Answers:


249

ObservableCollection <T>具有一个构造函数重载 ,该重载使用IEnumerable <T>

清单示例int

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

清单清单的另一个示例ObjectA

ObservableCollection<ObjectA> myCollection = new ObservableCollection<ObjectA>(myList as List<ObjectA>);

与创建扩展方法相比,我更喜欢这样做。帮助减少依赖性计数。
markokstate

1
反之亦然?
阿伦·普拉萨德

19

ObervableCollection具有可在其中传递列表的构造函数。引用MSDN

 public ObservableCollection(
      List<T> list
 )

6

Observable Collection构造函数将采用IList或IEnumerable。

如果发现要执行很多操作,则可以制作一个简单的扩展方法:

    public static ObservableCollection<T> ToObservableCollection<T>(this IEnumerable<T> enumerable)
    {
        return new ObservableCollection<T>(enumerable);
    }
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.