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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 00:59:27  来源:igfitidea点击:

Convert a List<T> into an ObservableCollection<T>

c#windows-runtime

提问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

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

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

 public ObservableCollection(
      List<T> list
 )

回答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);
    }