tags:

views:

816

answers:

4

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();
}
+3  A: 

You can call the ToList LINQ extension Method

List<Student> selectedCollection = selected.ToList<Student>();
foreach (Student s in selectedCollection)
{
    s.Show();
}
Michael G
+5  A: 

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();
CMS
This answer has a better explanation than my own. This should be accepted.
Michael G
+1  A: 

Try the following

List<Student> selectedCollection = selected.ToList();
JaredPar
+6  A: 

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.

adrianbanks