开发者

C# - var to List<T> conversion

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;开发者_如何学Go
foreach (Student s in selectedCollection)
{
    s.Show();
}


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜