C# - var转换为List<T>

10

如何将var类型转换为List类型?

以下代码段给出了错误提示:

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();
}

2
var 不是一种类型,它只是一个占位符,用于指定变量分配的表达式的类型。在这种情况下,查询表达式计算为 IEnumerable<Student> - Joren
4个回答

24

当你执行Linq to Objects查询时,它将返回类型IEnumerable<Student>,你可以使用ToList()方法从IEnumerable<T>创建一个List<T>

var selected = from s in studentCollection
                           select s;

List<Student> selectedCollection = selected.ToList();

1
这个答案的解释比我的好。应该被接受。 - Michael G
@CMS 你好,我的朋友。我在我的项目中尝试了这个解决方案,但它对我没有起作用。你能帮我解决这个问题吗? http://stackoverflow.com/questions/32839483/how-can-change-list-type - CoderWho

8
在你的示例代码中,var 实际上被类型化为 IEnumerable<Student>。如果你所要做的只是枚举它,那么没有必要将其转换为列表。
var selected = from s in studentCollection select s;

foreach (Student s in selected)
{
    s.Show();
}

如果你确实需要它作为一个列表,Linq 中的 ToList() 方法将会为你转换成一个列表。

3
您可以调用ToList LINQ扩展方法。
List<Student> selectedCollection = selected.ToList<Student>();
foreach (Student s in selectedCollection)
{
    s.Show();
}

1

请尝试以下操作

List<Student> selectedCollection = selected.ToList();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接