如何在C#中将特定行从DataTable复制到另一个DataTable?有多行。
foreach (DataRow dr in dataTable1.Rows) {
if (/* some condition */)
dataTable2.Rows.Add(dr.ItemArray);
}
以上示例假设dataTable1
和dataTable2
拥有相同数量、类型和顺序的列。
从一个表复制指定行到另一个表
// here dttablenew is a new Table and dttableOld is table Which having the data
dttableNew = dttableOld.Clone();
foreach (DataRow drtableOld in dttableOld.Rows)
{
if (/*put some Condition */)
{
dtTableNew.ImportRow(drtableOld);
}
}
DataTable::Rows::Add(...)
相比,DataTable::ImportRow
在处理列的数量和顺序时更加宽容。如果导入的行中缺少某一列,则该值将被设置为 NULL。 - AlainD试试这个
String matchString="ID0001"//assuming we have to find rows having key=ID0001
DataTable dtTarget = new DataTable();
dtTarget = dtSource.Clone();
DataRow[] rowsToCopy;
rowsToCopy = dtSource.Select("key='" + matchString + "'");
foreach (DataRow temp in rowsToCopy)
{
dtTarget.ImportRow(temp);
}
看一下这个,你可能会喜欢它(之前,请将table1克隆到table2):
table1.AsEnumerable().Take(recodCount).CopyToDataTable(table2,LoadOption.OverwriteChanges);
或:table1.AsEnumerable().Where ( yourcondition ) .CopyToDataTable(table2,LoadOption.OverwriteChanges);
支持版本:4、3.5 SP1。您现在可以直接调用对象上的方法。
DataTable dataTable2 = dataTable1.Copy()
DataTable destTable = sourceTable.Clone();
sourceTable.AsEnumerable().Where(row => /* condition */ ).ToList().ForEach(row => destTable.ImportRow(row));
sourceTable
,那么destTable
也会被清空吗? - Si8 DataTable newTable = oldtable.Clone();
for (int i = 0; i < oldtable.Rows.Count; i++)
{
DataRow drNew = newTable.NewRow();
drNew.ItemArray = oldtable.Rows[i].ItemArray;
newTable.Rows.Add(drNew);
}
for
,而是使用 foreach (Datarow dr...)
。 - Freerey// Generate DataTable[] alltables from multiple datatables
DataTable newTable = alltables[0].Clone();
foreach (DataTable dt in alltables)
{
for (int i = 0; i < dt.Rows.Count; i++)
newTable.Rows.Add(dt.Rows[i].ItemArray);
}
DataRow dr = dataset1.Tables[0].NewRow();
for (int i = 0; i < dataset1.Tables[1].Columns.Count; i++)
{
dr[dataset1.Tables[1].Columns[i].ColumnName] = dataset1.Tables[1].Rows[0][i];
}
datasetReport.Tables[0].Rows.Add(dr);
将索引0更改为您指定的行索引或者如果您要循环或者逻辑上需要,可以使用变量:
dataset1.Tables[1].Rows[0][i];
private void CopyDataTable(DataTable table){
// Create an object variable for the copy.
DataTable copyDataTable;
copyDataTable = table.Copy();
// Insert code to work with the copy.
}
ItemArray
部分时才会发生那种情况。确保添加的是行的值而不是行本身。 - Bradley SmithDataTable.Clone
方法的说明:http://msdn.microsoft.com/zh-cn/library/system.data.datatable.clone.aspx。 - Bradley Smith