【问题标题】:Can the select extension method project to a list of instantiated objects可以选择扩展方法投影到实例化对象列表
【发布时间】:2011-03-24 11:13:55
【问题描述】:

我有两个列表声明如下:

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

我正在尝试做这样的事情:

我有一个返回 List(Of AppItem) 的函数:

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

在上面的函数中,我填充 lstDBItems,然后编写如下返回语句:

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

奇怪的是代码可以编译,但在运行时我得到一个类型大小写错误。做我想要实现的目标的正确方法是什么......?

PS:请原谅截图被篡改。

【问题讨论】:

  • 如果您有 Option Strict On 则不会编译

标签: .net vb.net extension-methods


【解决方案1】:

代码不应该编译开始。检查您是否启用了 Option Strict。

一旦你弄清楚为什么它不应该编译,你的选择是:

  • 在查询结束时调用ToList,如下所示:

    Return lstDBItems.Select(Function(x)
                                dim oItem As New AppItem()
                                oItem.Property1 = x.DbProperty1
                                '...
                                Return oItem
                             End Function).ToList()
    
  • 将返回类型改为IEnumerable(Of AppItem)

【讨论】:

    【解决方案2】:

    Select 之后添加ToList() 以将List(Of AppItem) 作为返回值

    【讨论】:

      【解决方案3】:

      Select 方法的结果是IEnumerable(Of AppItem) 类型的,不能将其分配给List(Of AppItem 类型的变量)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-05-13
        • 2014-08-12
        • 2011-07-30
        相关资源
        最近更新 更多