簡體   English   中英

如何從另一個數據表向數據表添加列

[英]How to add column to datatable from another datatable

我有兩個數據表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的新行。

您可以使用DataTable.Merge方法。 命令dt1.Merge(dt2)添加到dt1的附加列和從附加數據記錄dt2 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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM