Imran Khan
Imran Khan

Reputation: 39

Linq query conversion from Ilist<> to List<>

I receive IList<> data and stores them like this:

 IList<Student> StudentList = DataKilde.Studenter();

Now I want to read them into a List<Student>:

List<Student> studentWhere3 = StudentList.Where(x=> x.StudentId > 2 && x.StudentId < 8).ToList(); 

This is working...becoz I think .ToList converts it to Ilist<> to List<>?

My problem is, when I am doing this:

List<Student> studentWhere5 = from s in StudentList
                              where s.StudentId==2
                              select s

I get a conversion error and have tried these:

from s in (List<Student>)StudentList

from s in StudentList as List<Student>

But it's not working.. I don't get why ?

Upvotes: 2

Views: 748

Answers (1)

CodeCaster
CodeCaster

Reputation: 151594

That's because select s returns an IQueryable<Student>, which is not implicitly nor explicitly convertable to a List<Student>, because there is no inheritance between the two.

You need to materialize the query result into a list:

(from s in StudentList
where s.StudentId==2
select s).ToList();

This will take all elements from the source collection (s) and store them in a List<Student>, which implements IList<Student>.

Upvotes: 6

Related Questions