C# DataTable 内连接与动态列

C# DataTable Inner join with dynamic columns(C# DataTable 内连接与动态列)

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

问题描述

我正在尝试以与此问题类似的方式将两个数据表连接在一起:

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

C#中DataTables的内连接

我试图让输出成为一个组合"表,其中包含两个原始表中的列.它们都有一个共同的日期戳列.

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.

给出的答案对于具有固定列的 DataTables 来说很好,但是如果它们是动态创建的,并且可以有任意数量的列,我该如何加入它们呢?

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.

它使用合并"方法,我之前认为这两个表需要相同的结构而忽略了该方法.

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);

注意:Merge 方法要求第二个参数为 false,否则它会复制结构,但不会复制第二个表的数据.

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.

这将合并以下表格:

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 内连接与动态列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:C# DataTable 内连接与动态列

基础教程推荐