【问题标题】:How to add column to datatable from another datatable如何将列从另一个数据表添加到数据表
【发布时间】:2016-09-22 03:10:49
【问题描述】:

我有两个数据表 dt1 和 dt2,它们共享一个公共列。如何映射公用列并在数据表 dt1 中添加包含数据的新列。

DataTable dt1=new DataTable();
DataTable dt2=new DataTable();

sqlDataAdapter da1=new sqlDataAdapter("select col1,col2,col3,col4 from table",connection);
dataset ds1=new dataset();
da1.fill(ds);
dt1=ds.tables[0];

同样,对于 dt2,select 语句是“select col1,somecol from sometable”,其余与 dt1 相同。

dt1 的输出是: dt2 的输出

col1   col2  col3 col4             col1  somecol
1        2     3   4                1     true
2        5     6   ...              2     false..

我尝试如下:

datatable dtTotal=new datatable();
dtTotal=dt1.clone();
foreach(datacolumn col in dt2.columns)
{
if(col.columnname=="somecol")
{
dtTotal.columns.add("somecol");
dtTotal.columns["somecol"].Datatype=col.Datatype;
}
}
foreach(datarow dr in dt1.rows)
{
dtTotal.importrows(dr);
}
//here a column is added but i don't understand how to import data into that column

我想要一个像下面这样的输出:

col1 col2 col3 col4  somecol
1      2   3    4      true
2      5   6    7      false...

在选择数据本身时,我无法编写简单的连接,因为 dt2 数据来自更复杂的计算。所以我只能在数据表级别进行。

如果 dt1 中的行数与 dt2 中的行数不匹配,则 dt2 应添加新行,默认值为 false。

【问题讨论】:

    标签: c# asp.net datatable


    【解决方案1】:

    您可以使用DataTable.Merge 方法。命令dt1.Merge(dt2) 将附加列和来自dt2 的附加数据记录添加到dt1。来自dt2 的数据将覆盖来自dt1 的具有相同主键值和相同列名的数据。

    DataTable dt1 = new DataTable();
    DataTable dt2 = new DataTable();
    
    // Fill the data tables
    ...
    
    // Set the default value for boolean column
    dt2.Columns[4].DefaultValue = false;
    
    // Set the primary keys
    dt1.PrimaryKey = new DataColumn[] { dt1.Columns[0] }; // Use the appropriate column index
    dt2.PrimaryKey = new DataColumn[] { dt2.Columns[0] }; // Use the appropriate column index
    
    // Merge the two data tables in dt1
    dt1.Merge(dt2);
    

    【讨论】:

      猜你喜欢
      • 2010-11-22
      • 1970-01-01
      • 1970-01-01
      • 2014-05-17
      • 1970-01-01
      • 2016-12-16
      • 2013-07-28
      • 2010-10-25
      • 1970-01-01
      相关资源
      最近更新 更多