[英]Copying specific columns from one datatable to another
This doesn't seem like something that should be confusing or difficult, but I'm having a hard time finding the answer to this problem. 这似乎不应该引起混淆或困难,但是我很难找到解决这个问题的方法。 I want to copy columns with their data, not rows, from one large DataTable to a smaller one.
我想将包含数据而不是行的列从一个大的DataTable复制到一个较小的DataTable。
I have a DataTable with many columns of data (around 20), and a string array of the columns (4 ) that I want in the copied DataTable. 我有一个DataTable,其中包含许多数据列(大约20列),以及要在复制的DataTable中包含的列的字符串数组(4)。 Is there a reasonable way to accomplish this task?
有合理的方法来完成此任务吗?
You can clone the table, remove the columns you don't need, then perform a merge. 您可以克隆表,删除不需要的列,然后执行合并。 Thanks to Yuriy's helpful comment, this cuts the code down significantly.
感谢Yuriy的有用评论,这大大减少了代码。
Dim columnsToKeep As String() = {"ColumnName1", "ColumnName2"}
Dim destTable As DataTable = sourceTable.Clone()
For index As Integer = destTable.Columns.Count - 1 To 0 Step - 1
Dim columnName As String = destTable.Columns(index).ColumnName
If Not columnsToKeep.Contains(columnName) Then
destTable.Columns.RemoveAt(index)
End If
Next
destTable.Merge(sourceTable, False, MissingSchemaAction.Ignore)
The MissingSchemaAction.Ignore
will perform the merge and ignore the extra columns found in the sourceTable
. MissingSchemaAction.Ignore
将执行合并,并忽略在sourceTable
找到的额外列。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.