How to combine and retrieve multiple columns from two tables in a Dataset

a 夏天 提交于 2019-12-13 21:12:50

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!