【发布时间】:2016-08-18 12:57:58
【问题描述】:
我正在编写一个使用 LINQ 连接两个 DataTables 的函数,问题是我事先不知道这两个表包含哪些列,除了表将被连接的列。
string id = "ID";
DataTable tableJoined = new DataTable();
tableJoined.Columns.Add(id, typeof(string));
tableJoined.Columns.Add("NAME", typeof(string));
tableJoined.Columns.Add("STOCK", typeof(string));
var result = from dataRows1 in table1.AsEnumerable()
join dataRows2 in table2.AsEnumerable()
on dataRows1.Field<string>(id) equals dataRows2.Field<string>(id)
select tableJoined.LoadDataRow(new object[]
{
dataRows1.Field<string>(id),
dataRows1.Field<string>(1),
dataRows2.Field<string>(1)
}, false);
result.CopyToDataTable();
我可以构建tableJoined 数据表并随时添加列以适应tableJoined 的最终结构,但是如何更新LINQ 查询以使用所有可用字段填充tableJoined?现在它只通过知道表包含多少列来填充“ID”、“NAME”和“STOCK”。谢谢。
【问题讨论】: