水平合并两个数据表列 [英] merge two datatable columns horizontaly
问题描述
嗨大家好
关于如何合并这样两个数据表的任何想法
表1
1 | 3 | 5 |
表2
| 2 | 4 | 6 |
成为
1 | 2 | 3 | 4 | 5 | 6
谢谢
Hi Guys
Any idea on how to merge two datatable like this
table 1
1 | 3 | 5 |
table 2
| 2 | 4 | 6 |
to become
1 | 2 |3 |4 |5 |6
thanks
推荐答案
试试这个...
我创建了类似于帖子中的表格
Try this ...
I created tables similar to those you have in your post
DataTable table1 = new DataTable();
DataTable table2 = new DataTable();
table1.Columns.Add("1", typeof(string));
table1.Columns.Add("3", typeof(string));
table1.Columns.Add("5", typeof(string));
table2.Columns.Add("2", typeof(string));
table2.Columns.Add("4", typeof(string));
table2.Columns.Add("6", typeof(string));
然后我创建了一个数据表来保存结果
Then I created a datatable to hold the results
DataTable dtResult = new DataTable();
dtResult.Columns.Add("1", typeof(string));
dtResult.Columns.Add("2", typeof(string));
dtResult.Columns.Add("3", typeof(string));
dtResult.Columns.Add("4", typeof(string));
dtResult.Columns.Add("5", typeof(string));
dtResult.Columns.Add("6", typeof(string));
然后我利用DataTable可以转换为可查询对象的事实
I then take advantage of the fact that DataTable can be converted to a queryable object
var t1 = table1.AsEnumerable();
var t2 = table2.AsEnumerable();
我不得不假设行号是通往加入这两个表并使用它来填充结果
I had to make the assumption that the "row number" was the way to join the two tables and used this to populate the result
var result = from dataRows1 in t1
join dataRows2 in t2
on table1.Rows.IndexOf(dataRows1) equals table2.Rows.IndexOf(dataRows2) into lj
from r in lj.DefaultIfEmpty()
select (new object[]
{
dataRows1.Field<string>("1"),
r.Field<string>("2"),
dataRows1.Field<string>("3"),
r.Field<string>("4"),
dataRows1.Field<string>("5"),
r.Field<string>("6")
});
foreach (var x in result)
dtResult.Rows.Add(x);
总结 - 我使用了< a href =https://msdn.microsoft.com/en-us/library/bb397895.aspx>左连接 [ ^ ]在表格中选择了我需要的列
In summary - I used a Left Join[^] on the tables and selected the columns I needed in the order you required
这篇关于水平合并两个数据表列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!