C# - var 到 List<T> 的转换
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1551273/
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
C# - var to List<T> conversion
提问by user366312
How to cast/convert a var type to a List type?
如何将 var 类型转换/转换为 List 类型?
This code snippet is giving me error:
这段代码片段给了我错误:
List<Student> studentCollection = Student.Get();
var selected = from s in studentCollection
select s;
List<Student> selectedCollection = (List<Student>)selected;
foreach (Student s in selectedCollection)
{
s.Show();
}
回答by CMS
When you do the Linq to Objects query, it will return you the type IEnumerable<Student>
, you can use the ToList()
method to create a List<T>
from an IEnumerable<T>
:
当您执行 Linq to Objects 查询时,它会返回类型IEnumerable<Student>
,您可以使用该ToList()
方法List<T>
从 an创建一个IEnumerable<T>
:
var selected = from s in studentCollection
select s;
List<Student> selectedCollection = selected.ToList();
回答by adrianbanks
The var
in your sample code is actually typed as IEnumerable<Student>
. If all you are doing is enumerating it, there is no need to convert it to a list:
在var
您的示例代码实际上是类型为IEnumerable<Student>
。如果您所做的只是枚举它,则无需将其转换为列表:
var selected = from s in studentCollection select s;
foreach (Student s in selected)
{
s.Show();
}
If you do need it as a list, the ToList()method from Linq will convert it to one for you.
如果您确实需要将其作为列表,Linq的ToList()方法会为您将其转换为列表。
回答by Michael G
You can call the ToList LINQ extension Method
可以调用 ToList LINQ 扩展方法
List<Student> selectedCollection = selected.ToList<Student>();
foreach (Student s in selectedCollection)
{
s.Show();
}
回答by JaredPar
Try the following
尝试以下
List<Student> selectedCollection = selected.ToList();