C# - var to List<T> conversion

user366312 picture user366312 · Oct 11, 2009 · Viewed 73.7k times · Source

How to cast/convert a var type to a List type?

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

Answer

Christian C. Salvad&#243; picture Christian C. Salvadó · Oct 11, 2009

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>:

var selected = from s in studentCollection
                           select s;

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