将数据表中的行复制到数据行,然后复制到另一个数据表中 vb.net

Copy row from dataTable to datarow and then to another dataTablein vb.net

如何将数据表中的一行传输到数据行,然后将数据行传递到新的数据表

Public function fn_transfer(dt as dataTable) 

Dim dtNew as new dataTable

dtNew = dt.Clone()

For i as integer= 0 to dt.rows.count -1 

If dt.rows(i)("name").ToString.trim = "" or 
dt.rows(i)("street").ToString.trim = "" then

Dim dr() as new datarow
For each dr in dt.rows(i)
dr = dt.Rows(i).Itemarray

Next


dtNew.importrow(dr(0))

Next

此代码无效。请纠正代码。

所以您只想导入 Name 或 Street 为空的那些行?

如果您想使用循环,这应该可行:

For Each r As DataRow in dt.rows
    If String.IsNullOrEmpty(r.Field(Of String)("Name")) OrElse String.IsNullOrEmpty(r.Field(Of String)("Steet"))
      dtNew.importrow(row)          
    End If
Next

另一种方法是使用 LINQ 和 CopyToDataTable:

Dim dtNew as DataTable = dt.Clone() ' empty table with same columns
Dim filteredRows = dt.AsEnumerable().
    Where(Function(r) String.IsNullOrEmpty(r.Field(Of String)("Name")) OrElse String.IsNullOrEmpty(r.Field(Of String)("Steet"))).
    ToList()

If filteredRows.Any() Then dtNew = filteredRows.CopyToDataTable()