C# 将 List<T> 转换为 ObservableCollection<T>
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16432450/
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
Convert a List<T> into an ObservableCollection<T>
提问by raghu_3
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.
我有一个List<T>从 JSON 填充的。我需要将其转换为 anObservableCollection<T>以将其绑定到我的GridView.
Any suggestions?
有什么建议?
采纳答案by Denis
ObservableCollection < T > has a constructor overloadwhich takes IEnumerable < T >
ObservableCollection < T > 有一个构造函数重载,它接受 IEnumerable < T >
Example for a List of int:
列表示例int:
ObservableCollection<int> myCollection = new ObservableCollection<int>(myList);
One more example for a List of ObjectA:
列表的另一个示例ObjectA:
ObservableCollection<ObjectA> myCollection = new ObservableCollection<ObjectA>(myList as List<ObjectA>);
回答by Piotr Stapp
回答by PaulC
The Observable Collection constructor will take an IList or an IEnumerable.
Observable Collection 构造函数将采用 IList 或 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);
}

