C# 如何从其他数据表创建具有列结构的新数据表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19009436/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 13:52:59  来源:igfitidea点击:

How to create new DataTable with column structure from other DataTable?

c#datatable.net-4.5

提问by Kamil

As in title - the question is:

正如标题 - 问题是:

How to create new DataTable with column structure from other DataTable?

如何从其他数据表创建具有列结构的新数据表?

I need empty DataTable to use .Rows.Add()method in it.

我需要空的 DataTable 才能.Rows.Add()在其中使用方法。

Code:

代码:

DataTable dtFirst = new DataTable();
dtFirst.Columns.Add("column1");
dtFirst.Columns.Add("column2");
dtFirst.Columns.Add("column3");

FillDataTableFirst(); // before I create second DataTable - dtFirst is filled

// here I need dtSecond DataTable with same column structure
// i cant just copy first data table, because it contains data

DataTable dtSecond = ???;

采纳答案by Bridge

You are looking for the DataTable.Clone()method (available since framework version 1.1).

您正在寻找该DataTable.Clone()方法(自框架版本 1.1 起可用)。

From the documentation:

文档

Clone creates a new DataTable with the same structure as the original DataTable, but does not copy any data (the new DataTable will not contain any DataRows). To copy both the structure and data into a new DataTable, use Copy.

Clone 创建一个与原始 DataTable 具有相同结构的新 DataTable,但不复制任何数据(新 DataTable 将不包含任何 DataRow)。要将结构和数据都复制到新的 DataTable 中,请使用 Copy。

In your example:

在你的例子中:

DataTable dtFirst = new DataTable();
dtFirst.Columns.Add("column1");
dtFirst.Columns.Add("column2");
dtFirst.Columns.Add("column3");

FillDataTableFirst(); // before I create second DataTable - dtFirst is filled

DataTable dtSecond = dtFirst.Clone();

回答by acermate433s

use the Clone()method of the DataTable class.

使用DataTable 类的Clone()方法。

回答by Tim Schmelter

Just use DataTable.Clonewhich clones the schema but not the data:

只需使用DataTable.Clonewhich 克隆模式而不是数据:

DataTable dtSecond = dtFirst.Clone(); // empty

Now you can start adding new rows:

现在您可以开始添加新行:

DataRow newRow = dtSecond.Rows.Add();
newRow.SetField("column1", "Value1");
newRow.SetField("column2", "Value2");
newRow.SetField("column3", "Value3");