将一个数据表的列添加到另一个数据表

时间:2009-08-24 15:16:54

标签: c# asp.net datatable

嘿所有人都需要帮助为这个表排序一个循环,似乎无法将一个工作示例应用到模型中,无论如何它都在这里。

我有2个数据表,每个数据表具有不同的数据和不同的值,唯一的共同值是日期。第一个表包含我想要的所有内容,除了一列值(来自另一个表)所以我需要将此列合并到第一个表,而不是所有其他数据。

理想情况下,我想要一些看起来像这样的东西:

DataTable tbl1; //Assume both are populated
DataTable tbl2;

tbl1.Columns.Add("newcolumnofdata") //Add a new column to the first table

foreach (DataRow dr in tbl.Rows["newcolumnofdata"]) //Go through each row of this new column
{
    tbl1.Rows.Add(tbl2.Rows["sourceofdata"]); //Add data into each row from tbl2's column.
    tbl1.Columns["date"] = tbl2.Columns["date"]; //The date field being the same in both sources
} 

如果有人可以帮助wud欣赏它,就像我说我只需要一列,我不需要拥有整个其他数据表。欢呼声。

2 个答案:

答案 0 :(得分:7)

如果第二个表已经包含所有行,但只缺少一列 它应该足以做这样的事情

DataTable tbl1;
DataTable tbl2;

tbl1.Columns.Add("newCol");

for(int i=0; i<tbl.Rows.Count;i++)
{
   tbl1.Rows[i]["newcol"] = tbl2.Rows[i]["newCol"];
   tbl1.Rows[i]["date"] = tbl2.Rows[i]["date"];
}

答案 1 :(得分:2)

假设行计数匹配且排序正确,您应该能够这样做......

for(int i = 0; i < tbl1.Rows.Count; i++)
{
    tbl1.Rows[i]["newcolumnofdata"]= tbl2.Rows[i]["newcolumnofdata"];
}

我不确定date作业的来源。