Question

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();
}
Was it helpful?

Solution

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

OTHER TIPS

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

You can call the ToList LINQ extension Method

List<Student> selectedCollection = selected.ToList<Student>();
foreach (Student s in selectedCollection)
{
    s.Show();
}

Try the following

List<Student> selectedCollection = selected.ToList();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top