问题描述
这似乎不应该引起混淆或困难,但是我很难找到解决该问题的方法。我想将带有数据而不是行的列从一个大的DataTable复制到一个较小的DataTable。
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.
我有一个包含许多数据列(大约20个)的DataTable,以及我想要的复制DataTable中的列(4)的字符串数组。有合理的方法来完成此任务吗?
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. Is there a reasonable way to accomplish this task?
推荐答案
您可以克隆表,删除不需要的列,然后执行合并。感谢Yuriy的有用评论,这大大减少了代码。
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.
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)
MissingSchemaAction.Ignore
将执行合并,并忽略在 sourceTable
中找到的多余列。
The MissingSchemaAction.Ignore
will perform the merge and ignore the extra columns found in the sourceTable
.
这篇关于将特定的列从一个数据表复制到另一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!