views:

33

answers:

1

Hi,

I run into this problem

System.InvalidCastException: Unable to cast object of type 'System.Data.Linq.DataQuery1[Student]' to type 'System.Collections.Generic.List1[Student]'

When I debug this function:

Public Shared Function SearchStudent(ByVal firstname As String) As List(Of Student)

    Dim db As New DemoDataContext()
    Dim query = From st In db.Students _
                Where (st.FirstName.StartsWith(firstname)) _
                Select st

    Return CType(query, List(Of Student))


End Function

My project property setting: Option explicit ON and Option strict ON

I want to return a List of Student from the query. Can anyone help me? Thank you.

+1  A: 
    Dim query = (From st In db.Students _
            Where (st.FirstName.StartsWith(firstname)) _
            Select st).ToList()
Kthurein
query.ToList(Of Student) will also do the job.
Kthurein
I tried that option before I posted this question. But I got this error Extension method 'Public Function ToList() As System.Collections.Generic.List(Of TSource)' defined in 'System.Linq.Enumerable' is not generic (or has no free type parameters) and so cannot have type arguments
Narazana
How about .ToList() ? I think you can omit the type parameter since it can be inferred from the usage.
Kthurein
Yes, I used .ToList() only and Return query. I dont understand why I can't CType query.
Narazana
To my knowledge, it is because of IEnumerable which doesn't support either implicit or explicit conversion to List(Of T).
Kthurein
The reason is that the LINQ query is not a List! You need to read up on deferred execution of LINQ queries. The actual Sql query does not happen until the ToList() method is called.
Chris Dunaway