问题描述
我们如何从一个数据表中复制一个DataColumn的数据到另一个数据表?我有数据表像
How can we copy one datacolumn with data from one datatable to another datatable ? I have datatable like
DataTable datatable1=new DataTable();
和有该表四列,但我想只有一个column.So我做喜欢
and there are four columns in that table but I want only one column.So I am doing like
DataTable datatable2=new DataTable();
addressAndPhones2.Columns.Add(addressAndPhones.Columns[0].ColumnName,addressAndPhones.Columns[0].DataType);
不过这只是增加了列,但我希望将数据复制该列到datatable2.That是我想从一个数据表中复制与数据的DataColumn到另一个数据表。
but this just adds the column but I want to copy the data for that column to the datatable2.That is I want to copy the datacolumn with data from one datatable to another datatable.
推荐答案
两种解决方案涌现在脑海:
Two solutions spring to mind:
- 通过所有行创建柱,循环到数据从源到目标复制之后。
- 请一个datatable1.Copy()来复制所有列+数据并删除那些你不需要的。
- after creating the column, loop through all rows to copy the data from the source to the target.
- Do a datatable1.Copy() to copy all columns+data and delete the ones you don't need.
第二个是简单code,但将拷贝不需要的数据(这意味着额外的时间和内存)。
The second one is simpler to code but will copy unneeded data (which means extra time and memory).
对于第一个,如果你有prepared的命运,数据表和源和命运columnnames(和类型)是相同的:
For the first one, IF you have prepared the destiny-datatable AND the columnnames (and types) in source and destiny are the same:
private void CopyColumns(DataTable source, DataTable dest, params string[] columns)
{
foreach (DataRow sourcerow in source.Rows)
{
DataRow destRow = dest.NewRow();
foreach(string colname in columns)
{
destRow[colname] = sourcerow[colname];
}
dest.Rows.Add(destRow);
}
}
您可以使用此类似:
CopyColumns(source, destiny, "Column1", "column2");
命名任意数量的列。
naming any number of columns.
这篇关于我们怎样才能DataTable的DataColumn上的数据复制到另一个数据表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!