开发者

Can the select extension method project to a list of instantiated objects

I have two lists declared as fo开发者_开发百科llows:

Dim lstDBItems As New List(Of DBItem)
Dim lstAppItems As New List(Of AppItem)

I am trying to do something like this:

I've a function which returns List(Of AppItem):

Function GetAppItems() As List(Of AppItem)
'...
End Function

In the above function I populate lstDBItems and then write the return statement like follows:

Return lstDBItems.Select(Function(x)
                            dim oItem As New AppItem()
                            oItem.Property1 = x.DbProperty1
                            '...
                            Return oItem
                        End Function)

The weird thing is the code compiles, but on rumtime I get a type case error. What is the correct way of doing what I'm trying to achieve...?

PS: Excuse the screenshot tampering.

Can the select extension method project to a list of instantiated objects


The code shouldn't compile to start with. Check that you've got Option Strict on.

Once you've worked out why it's compiling when it shouldn't, your options are:

  • Call ToList at the end of the query, like this:

    Return lstDBItems.Select(Function(x)
                                dim oItem As New AppItem()
                                oItem.Property1 = x.DbProperty1
                                '...
                                Return oItem
                             End Function).ToList()
    
  • Change the return type to IEnumerable(Of AppItem)


Add ToList() after the Select to have a List(Of AppItem) as return value


The result of the Select method is of type IEnumerable(Of AppItem), which can not be assigned to a variable of type List(Of AppItem).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜