C# 如何在 wpf 中将 List<T> 转换为 ObservableCollection<T>?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18095932/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to cast a List<T> to an ObservableCollection<T> in wpf?
提问by
I am in wpf, and have a generic list: List. Now I wish to cast it to a generic observable collections: ObservableCollection.
我在 wpf,有一个通用列表:List。现在我希望将它转换为一个通用的可观察集合: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.
我知道我可以遍历列表并将每个单独的项目添加到 Observable 集合中。但是,在我看来,必须有一种内置的方式来做到这一点。
采纳答案by Shaamaan
If you JUST want to create an ObservableCollection
from a List
, then all you need to do is
如果您只想ObservableCollection
从 a创建一个List
,那么您需要做的就是
ObservableCollection<MyType> obsCollection = new ObservableCollection<MyType>(myList);
回答by Ehsan
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 constructorThe elements are copied onto the ObservableCollection in the same order they are read by the enumerator of the list.
或者您可以使用此构造函数将元素按照列表的枚举器读取它们的相同顺序复制到 ObservableCollection 中。
ObservableCollection<YourObject> collection = new ObservableCollection<YourObject>(yourList);
回答by Nitesh
var _oc = new ObservableCollection<ObjectType>(_listObjects);
回答by Ravi Gadag
ObservableCollection has Conttructor for IEnumerable<T>
ObservableCollection
的ObservableCollection有Conttructor的IEnumerable<T>
的ObservableCollection
ObservableCollection<yourType> observable =
new ObservableCollection<yourType>(yourListObject);