【问题标题】:Linq returning list of anonymous typesLinq 返回匿名类型列表
【发布时间】:2009-03-11 09:52:32
【问题描述】:

Caan somone 建议我尝试实现的最佳方法(linq 到 sql,返回数据列表以显示在网格/列表等中)......它抱怨匿名类型转换,以及我从什么正在阅读,这不是优雅的做法。

  Public Function GetHistory(ByVal historyId As Integer) As List(Of ?????????)
    Using dc As New myDataContext(Application.GetConnection)
      Return (From t In dc.ActionTypes, a In t.MyTable Where a.HistoryID = historyId Select a.ActionOn, a.ActionBy, t.Description, a.ImpactedItem, a.ActionDescription).ToList
    End Using
  End Function

【问题讨论】:

    标签: asp.net vb.net linq linq-to-sql anonymous-types


    【解决方案1】:

    问题是匿名类型没有可用作函数返回值的编译时类型,所以 ????在你的 List(Of ????) 中是编译器无法知道的。

    由于您将其绑定到 UI 元素,因此最好的选择可能是将返回值设为 IEnumerable 或 IList。您应该能够将您的控件绑定到该控件(因为绑定在幕后使用反射)。

    【讨论】:

    • 作为通用 iList 返回完成了这项工作..... 最佳实践,值得怀疑... 可行,当然。
    【解决方案2】:

    匿名类型不能离开函数的作用域。所以你想要做的事情是不可能的。您必须创建一个可以使用返回类型的类型(结构或类)。

    【讨论】:

      【解决方案3】:

      http://blogs.msdn.com/swiss_dpe_team/archive/2008/01/25/using-your-own-defined-type-in-a-linq-query-expression.aspx

      定义您自己的数据类对象,例如MyClass 具有属性 ActionOn、ActionBy、Description、ImpactedItem、ActionDescription

      然后使用:

      Public Function GetHistory(ByVal historyId As Integer) As List(Of MyClass)
          Using dc As New myDataContext(Application.GetConnection)
              Return ( _
                  From t In dc.ActionTypes, a In t.MyTable _
                  Where a.HistoryID = historyId _
                  Select New MyClass _
                  With {.ActionOn=a.ActionOn, .ActionBy=a.ActionBy, ...} _
              ).ToList
          End Using
      End Function
      

      【讨论】:

      • 仅供参考,我在将 MyClass 作为类时遇到了问题(“无法显式初始化类”错误)-如果您得到相同的结果,请使用结构(您不需要构造函数-只是语法相同同上)
      【解决方案4】:

      您可以使用 te linq 函数 CAST,然后将列表转换为 Object 并返回 Object 的 Enumerable。

      Public Function GetHistory(ByVal historyId As Integer) As  List(Of Object)
      
          Using dc As New myDataContext(Application.GetConnection)
      
        Return (From t In dc.ActionTypes, a In t.MyTable Where _
                a.HistoryID = historyId Select a.ActionOn, a.ActionBy, _
                t.Description, a.ImpactedItem, a.ActionDescription) _
                .Cast(Of Object).ToList()
      
          End Using
      
      
      End Function
      

      【讨论】:

        【解决方案5】:

        如果该类是唯一将使用结果的类(尽管这似乎不太可能,因为您创建了函数Public),您可以创建一个嵌套类/结构来保存结果。否则,您想要做的事情是不可能的:匿名类型可能只有method scope

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-05-21
          • 1970-01-01
          相关资源
          最近更新 更多