问题
I have a DataSet with two tables connected by a reference (Loop_id)
Table1
Column1 Column2 Loop_id
1 ItemCode_AAA 6
2 ItemCode_BBB 8
Table2
Column1 Loop_id
2014-Sep-09 6
2014-Nov-09 8
How do I retrieve all the columns, except loop_id from both tables to single table. The resulting table should appear like
T1_Column1 T1_Column2 T2_Column1
1 ItemCode_AAA 2014-Sep-09
2 ItemCode_BBB 2014-Nov-09
I am using Net Framework 4.5
回答1:
Use Linq to DataSets:
To enumerate the table, call AsEnumerable
.
DataTable table1 = ds.Tables["table1"];
DataTable table2 = ds.Tables["table2"];
var records = (from t1 in table1.AsEnumerable()
join t2 in table2.AsEnumerable()
on t1.Field<int>("Loop_id") equals t2.Field<int>("Loop_id")
select new {T1_Column1 = t1.Field<string>("Column1"),
T2_Column2 = t2.Field<string>("Column2"),
T2_Column1 = t2.Field<string>("Column1")});
回答2:
Use View
Or you can use join
SELECT T1.Column1 AS T1_Col , T1.Column2 AS T1_Col , T2.Column1 AS T2_Col
FROM dbo.Table1 AS T1 RIGHT OUTER JOIN
dbo.Table2 AS T2 ON dbo.T1.Loop_id = dbo.T2.Loop_id
来源:https://stackoverflow.com/questions/26658696/how-to-combine-and-retrieve-multiple-columns-from-two-tables-in-a-dataset