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

标签 c# datatable .net-4.5

如标题 - 问题是:

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

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

代码:

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 = ???;

最佳答案

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

来自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.

在你的例子中:

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();

关于c# - 如何从其他数据表创建具有列结构的新数据表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19009436/

相关文章:

c# - 我应该用 TraceSource.TraceEvent 方法中的 id 参数来识别什么?

javascript - 使行可点击(复选框除外)

c# - 使用 row.Field<T>(col) 和基于行/列索引获取单元格值之间的区别

c# - 基于等待任务的队列

c# - 找不到类型或命名空间名称 'async'

c# - 等待的奇怪行为

c# - 甲骨文日期格式

c# - DLL 中有什么以及它是如何工作的?

java - Primefaces 链接打开电子邮件撰写窗口

c# - ListViewItem 不显示列上的实际文本