将一个数据表的一列添加到另一个 [英] Adding a Column of one datatable to another

查看:27
本文介绍了将一个数据表的一列添加到另一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿,所有人都需要帮助整理这个表的循环,似乎无法将一个工作示例应用于模型,无论如何都在这里.

Hey all need a lil help sorting a loop for this table out, cant seem to apply a working example to the model, anyway here it goes.

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

I have 2 datatables, each with different data and different values, the only value in common is the date. The first table has everything I want in it except a single column of values (from the other table) So I need to merge this column onto the first table, not all the other data with it.

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

So ideally I'd like something that looks like this:

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
} 

如果有人可以帮助我们欣赏它,就像我说我只需要一列,我不需要整个其他数据表.干杯.

If anyone can help out wud appreciate it, like I say I just need the one column, I don't need to have the whole of the other datatable. Cheers.

推荐答案

如果第二个表已经有所有行,但只缺少一列做这样的事情应该就足够了

if the second table already has all rows, but just one column is missing it should be enough to do something like this

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"];
}

这篇关于将一个数据表的一列添加到另一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆