vb.net - 从 System.Linq.EnumerableQuery 转换为 System.

我正在尝试将动态 LINQ 查询的结果放入数据表中。尝试将查询直接放入数据表中会出现此错误:

Unable to cast object of type 'System.Linq.EnumerableQuery`1[DynamicClass1]' to type 'System.Data.DataTable'.

我的代码是:

Dim query = tbl.AsEnumerable.AsQueryable.Select("new(it[""curr""] as Curry)")
Dim tbl As DataTable = query

我试过:

Dim query As IEnumerable(Of DataRow) = tbl.AsEnumerable.AsQueryable.Select("new(it[""curr""] as Curry)").Cast(Of DataRow)()
Dim tbl1 As DataTable = query.CopyToDataTable

但这给了我:

Unable to cast object of type 'DynamicClass1' to type 'System.Data.DataRow'.

最佳答案

    Public Shared Function ConvertIEnumerableToDataTableFromProperties(Of T)(ByVal list As IEnumerable(Of T)) As DataTable
        Dim table As New DataTable()
        Dim fields() As PropertyInfo = GetType(T).GetProperties()
        For Each field As PropertyInfo In fields
            table.Columns.Add(field.Name, field.PropertyType)
        Next
        For Each item As T In list
            Dim row As DataRow = table.NewRow()
            For Each field As PropertyInfo In fields
                row(field.Name) = field.GetValue(item)
            Next
            table.Rows.Add(row)
        Next
        Return table
    End Function

关于vb.net - 从 System.Linq.EnumerableQuery 转换为 System.Data.Datatable(使用动态 LINQ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11363811/

相关文章:

ruby-on-rails-3.1 - Rack 中间件如何重定向到我的 Rails 应用程序中的

wordpress - 更改站点 URL 后无法访问 Wordpress wp-admin

asp.net - 转移到服务器场中的不同服务器时,IsPostBack 为假?

asp.net-mvc-3 - 如何修复来自 Shibboleth 的 SAML SSO 后的浏览器

ajax - 为什么 GIF 动画在执行 AJAX 调用时停止工作?

sql-server-2005 - 如何在 SQL Server Reports RDL 中合并具有

ios - 我的 iOS 开发者证书或私钥在 git 中吗?

asp.net - 为什么 GetServerVariable ("HTTP_URL") 根据管道模

c# - 如何使用 IKVM 静态注册加密提供商?

unit-testing - 您如何为集成测试设置数据