简体   繁体   中英

Unable to cast object of type 'WhereSelectEnumerableIterator'2 to Person (VB.Net)

I know there are other threads on SO concerning this error, and know what the error means. However, I cannot figure where the fix code in my own case.

I need to return an IEnumerable(Of Person) from an API. Previously I used a For Each loop, but was investigating using (much) less code to achieve the same result. I'm not sure if I've shortcutted too far here (perhaps hoping for a one-line nirvana...)

Public Function [Get]() As IEnumerable(Of Person)
    Using dt As DataTable = LoadDataTable()
        Return New List(Of Person)() From {
            From dr In dt.Rows Select New Person() With {
                .FirstName = dr.Item("FirstName").ToString(),
                .Surname = dr.Item("Surname").ToString()
            }
        }
    End Using
End Function

The error is:

Unable to cast object of type 'WhereSelectEnumerableIterator`2[System.Object, MyApp.Models.Person]' to type 'MyApp.Models.Person'

I guessed at placing the .ToList() extension method in different places, but can't get it right. Can anyone advise if this is all possible in a single operation, or if I have no choice to but declare a New List variable?

To put what @Craig said into an answer, From expects a comma separated list of whatever type you're using(in this case Person ), not another collection.

If you want to create a list from a collection you need to use the contstructor:

Return New List(Of Person)(
    From dr In dt.Rows Select New Person() With {
        .FirstName = dr.Item("FirstName").ToString(),
        .Surname = dr.Item("Surname").ToString()
    }
)

But the better option would be to just call ToList on your LINQ query:

Return (From dr In dt.Rows Select New Person() With {
    .FirstName = dr.Item("FirstName").ToString(),
    .Surname = dr.Item("Surname").ToString()
}).ToList()

Also, if you find it preferable, there is the extension method format which is a bit less wordy:

Return dt.Rows.Select(Function(dr) New Person() With {
                          .FirstName = dr.Item("FirstName").ToString(),
                          .Surname = dr.Item("Surname").ToString()
                          }).ToList()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM