开发者

DataTable in C#

Let's say I have two DataTables DT1 and DT2 with a single row.

DT1 has 3 columns: Col1, 开发者_运维技巧Col2, and Col3

and

DT2 has 2 columns: ColA, ColB.

Is it possible to join these two DataTables horizontally so I get Col1, Col2, Col3, ColA, and ColB?


I thin you have to add new columns and copy data either in third table or in one of the existing table

    DataTable dt1 = new DataTable();

    dt1.Columns.Add("col1", typeof(string));
    dt1.Columns.Add("col2", typeof(string));
    dt1.Columns.Add("col3", typeof(string));

    DataTable dt2 = new DataTable();

    dt2.Columns.Add("cola", typeof(string));
    dt2.Columns.Add("colb", typeof(string));

    object[] row = {'1', '2', '3'};
    dt1.Rows.Add(row);

    object[] row1 = { 'a', 'b' };
    dt2.Rows.Add(row1);

    // Create columns in dt1
    dt1.Columns.Add("cola", typeof(string));
    dt1.Columns.Add("colb", typeof(string));

    // Copy data from dt2
    dt1.Rows[0]["cola"] = dt2.Rows[0]["cola"];
    dt1.Rows[0]["colb"] = dt2.Rows[0]["colb"];


So long as you simply want a collection you can bind to you can do the following:

var results = from rs1 in table1.Rows.Cast<DataRow>()
              join rs2 in table2.Rows.Cast<DataRow>() on rs1.Field<int>("col1") equals rs2.Field<int>("colA")                          
              select new { col1 = rs1.Field<int>("col1"), col2 = rs1.Field<string>("col3"), col3 = rs1.Field<string>("col3"), colA = rs1.Field<int>("colA"), colB = rs1.Field<string>("colB") };

You would not get a DataTable but an IEnumerable<T> collection of anonymous type objects as defined in the select statement. Obvoiusly i have just guessed the join criteria and the data type of the columns so you would have to specify those as appropriate for your actual data.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜