C#的DataTable内连接与动态列 [英] C# DataTable Inner join with dynamic columns

查看:261
本文介绍了C#的DataTable内连接与动态列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想加入两个DataTable一起以同样的方式对这个问题:

I'm trying to join two DataTables together in a similar way to this question:

内的数据表的加入在C#

我想要得到的输出是一个单一的组合拳表中,与来自原始表的列。他们都有一个共同的日期戳列。

I'm trying to get the output to be a single 'combined' table, with columns from both of the original tables. They will both have a datestamp column in common.

给出的答案是良好的数据表与固定列,但如果他们是动态创建的内容,并且可以有任意数量的列,我怎么能加入他们的行列?

The answer given is good for DataTables with fixed columns, but what if they are created dynamically, and can have any number of columns, how can I join them?

例如。

T1 (datestamp, t1Column1, t1Column2, t1ColumnN...)
T2 (datestamp, t2Column1, t2Column2, t2ColumnN...)

我想加入到创建以下内容:

I would like to join to create the following:

J1 (datestamp, t1Column1, t1Column2, t1ColumnN, ..., t2Column1, t2Column2, t2ColumnN...)

这可能吗?

推荐答案

我发现它不依赖于通过列循环的解决方案。

I found a solution which doesn't rely on looping through the columns.

它采用了合并的方法,我有previously驳回,因为我认为这两个表​​所需要的相同的结构。

It uses the 'Merge' method, which I had previously dismissed as I thought both tables required the same structure.

首先,您需要创建的两个数据表的主键:

First you need to create a primary key on the two data-tables:

// set primary key
T1.PrimaryKey = new DataColumn[] { T1.Columns["DateStamp"] };
T2.PrimaryKey = new DataColumn[] { T2.Columns["DateStamp"] };

接着两个表添加一个数据设定一个关系可以添加:

Then add both tables to a data-set so a relationship can be added:

// add both data-tables to data-set
DataSet dsContainer = new DataSet();
dsContainer.Tables.Add(T1);
dsContainer.Tables.Add(T2);

接下来,添加数据集的两个关键列之间的关系:

Next add the relationship between the two key columns in the data-set:

// add a relationship between the two timestamp columns
DataRelation relDateStamp = new DataRelation("Date", new DataColumn[] { T1.Columns["DateStamp"] }, new DataColumn[] { T2.Columns["DateStamp"] });
dsContainer.Relations.Add(relDateStamp);

最后,你可以第一个数据表,现在复制到一个新的组合拳的版本,然后在第二个合并:

Finally you can now copy the first data-table into a new 'combined' version, and then merge in the second:

// populate combined data
DataTable dtCombined = new DataTable();
dtCombined = T1.Copy();
dtCombined.Merge(T2, false, MissingSchemaAction.Add);

注:合并方法需要第二个参数是假的,否则它复制结构,但第二个表中没有数据。

Note: The Merge method requires the second argument to be false or else it copies the structure but not the data of the second table.

这会再结合下面的表格:

This would then combine the following tables:

T1 (2012-05-09, 111, 222)
T2 (2012-05-09, 333, 444, 555)

成基于主密钥的​​组合的版本:

into a combined version based on the primary-key:

J1 (2012-05-09, 111, 222, 333, 444, 555)

这篇关于C#的DataTable内连接与动态列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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