简体   繁体   中英

How to cast a List<T> to an ObservableCollection<T> in wpf?

I am in wpf, and have a generic list: List. Now I wish to cast it to a generic observable collections: ObservableCollection.

I understand I can iterate over the list and add each individual item to the Observable collection. However, it seems to me there has to be a built-in way of doing this.

如果只想从List创建ObservableCollection ,那么您要做的就是

ObservableCollection<MyType> obsCollection = new ObservableCollection<MyType>(myList);
var _oc = new ObservableCollection<ObjectType>(_listObjects);

you can do it by using extension method

public static ObservableCollection<T> ToObservableCollection<T>(this IEnumerable<T> coll)
{
    var c = new ObservableCollection<T>();
    foreach (var e in coll) c.Add(e);
    return c;
}

or you can use this constructor The elements are copied onto the ObservableCollection in the same order they are read by the enumerator of the list.

ObservableCollection<YourObject> collection = new ObservableCollection<YourObject>(yourList);

ObservableCollection has Conttructor for IEnumerable<T> ObservableCollection

ObservableCollection<yourType> observable = 
        new ObservableCollection<yourType>(yourListObject);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM