views:

62

answers:

3
+2  Q: 

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?

A: 

AFAIK no, the DataSet and DataTable do not support automatic joins. You'll have to do the join manually by adding new columns to a table and copying the column values over from the other tables.

stakx
+2  A: 

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"];
Muhammad Kashif Nadeem
A: 

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.

Ben Robinson
@Ben - That's a nice answer, but I'm thinking that the two tables described in the question do not have a common key. In other words, I believe he's asking to join tow potentially different types of data. So `Col1` in table1 might be an `int`, but `ColA` in table2 might be `varchar`.
Jason Evans
Jason is correct. They have no common key, they just carry a bunch of numbers.
Rabin
You can specify joins in linq in anyway you want by using multiple froms and putting the criteria in the where clause, this is just the simplest option for if you had a foreign key type relationship. If you could specify how to relate the rows in each table then i could update my answer with the relevent join.
Ben Robinson