无法将LINQ结果复制到数据表中 [英] Can't copy LINQ result into datatable

查看:39
本文介绍了无法将LINQ结果复制到数据表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我的LINQ查询:

Below is my LINQ query:

Dim JoinedResult = From t1 In temp.AsEnumerable() _
                   Group Join t2 In tbCity.AsEnumerable() _
                   On t1.Field(Of String)("City") Equals t2.Field(Of String)("city_name") _
                   Into RightTableResults = Group _
                   From t In RightTableResults.DefaultIfEmpty
                   Select New With 
                   {
                        .ID = t1.Item("ID"), 
                        .CID = If(t Is Nothing, 
                        1,  
                        t.Item("city_gid"))
                   }  

如何将值从"JoinedResult"复制到数据表?

How can I copy values from "JoinedResult" to a datatable?

注意:

  1. 我没有得到JoinedResult.CopyToDataTable()
  2. 我不想使用循环

推荐答案

CopyToDataTable .但是问题是您想从匿名类型从头开始"创建DataTable.那不行

CopyToDataTable仅是IEnumerable<DataRow>的扩展.因此,您必须从加入的DataTables中选择一个 DataRow:

CopyToDataTable is an extension for IEnumerable<DataRow> only. So you either have to select one DataRow from your joined DataTables:

Dim query =  From t1 In temp.AsEnumerable() _
             Group Join t2 In tbCity.AsEnumerable() _
             On t1.Field(Of String)("City") Equals t2.Field(Of String)("city_name") Into RightTableResults = Group 
             From t In RightTableResults.DefaultIfEmpty
             Select t1
Dim table = query.CopyToDataTable()

或使用使用反射的ObjectShredder ,因此不是最有效的方法( C#实现).

除此之外,为什么还需要DataTable?您还可以将匿名类型用作DataSource或创建一个自定义类,该类可以从查询结果中初始化.

Apart from this, why do you need the DataTable at all? You could also use the anonymous type as DataSource or create a custom class which you can initialize from the query result.

编辑:您还可以使用所需的列创建自定义DataTable,例如(根据您的评论):

Edit: You can also create a custom DataTable with the columns you need, for example(from your comment):

Dim tbTemp As New DataTable
tbTemp.Columns.Add("ID")
tbTemp.Columns.Add("CID")

Dim query = From t1 In temp.AsEnumerable()
            Group Join t2 In tbCity.AsEnumerable() On
            t1.Field(Of String)("City") Equals t2.Field(Of String)("city_name")
            Into RightTableResults = Group
            From t In RightTableResults.DefaultIfEmpty
            Select New With {.ID = t1.Item("ID"), .City_Gid = t.Item("city_gid")}
For Each x In query
    tbTemp.Rows.Add(x.ID, x.City_Gid)
Next

这篇关于无法将LINQ结果复制到数据表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆