使用LINQ连接两个数据表,并在其他数据表中获取结果

时间:2013-12-12 10:50:44

标签: asp.net .net vb.net linq datatable

我有两个数据表,我正在加入它们来选择一些匹配的记录,我需要一些来自tatatable的列作为一个新的结果集,我这样做

        Dim query4 = From x In dtblPolicyFormStopCodes.AsEnumerable() Join y In dtblPolicyFormLetterReq.AsEnumerable()
        On x.Field(Of String)("Code") Equals y.Field(Of String)("Code") _
        Select New With _
        { _
            .Code = x.Field(Of String)("Code"), _
            .Sequence = x.Field(Of Integer)("Sequence "), _
            .FieldDataType= x.Field(Of String)("FieldDataType"), _
            .FieldValue= y.Field(Of String)("FieldValue") _
        }

        MyNewDataTable = GetDynamicTableSchema()

        query4.Cast(Of DataRow).CopyToDataTable(MyNewDataTable, LoadOption.OverwriteChanges)

但我无法获得两个数据表的选定列的新数据表,请帮助我如何在“MyNewDataTable”中获取新的结果集或作为新的数据表

Public Function GetDynamicTableSchema() As System.Data.DataTable
    Dim tblDynamicTableDataMain As System.Data.DataTable = Nothing
    Try
        tblDynamicTableDataMain = New System.Data.DataTable("DynamicTableData")
        With tblDynamicTableDataMain
            .Columns.Add("Code")
            .Columns.Add("Sequence", System.Type.GetType("System.Int32"))
            .Columns.Add("FieldDataType")
            .Columns.Add("FieldValue")
        End With
        Return tblDynamicTableDataMain
    End Try
End Function

1 个答案:

答案 0 :(得分:1)

我通过这种方式实现了我的愿望功能

Dim dr As DataRow
Dim MyNewDataTable as Datatable = GetDynamicTableSchema()

Dim query = (From x In dtblPolicyFormStopCodes.AsEnumerable() Join y In dtblPolicyFormLetterReq.AsEnumerable()
            On x.Field(Of String)("Code") Equals y.Field(Of String)("Code")) _
            .Select(Function(a) As DataRow
                        dr = MyNewDataTable.NewRow()
                        dr("Code") = a.x.Field(Of String)("Code")
                        dr("Sequence") = a.x.Field(Of Integer)("Sequence")
                        dr("FieldDataType") = a.x.Field(Of String)("FieldDataType")
                        dr("FieldValue") = a.y.Field(Of String)("Fieldvalue")
                        Return dr
                    End Function)

MyNewDataTable = query.CopyToDataTable()