I am trying to inner join 2 DataTables on 2 DataColumns using Linq, I can get the rows using Linq how ever I cannot get the columns. I have commented out what I tried to do to get the columns, shown below.
The reason for doing this.
I am planning on making 3 methods, LEFT JOIN, FULL JOIN and INNER JOIN that will return a DataTable, I am trying to make it as generic as possible, I am not show if the below is a good way or not, I need to do this to be as Optimized as possible.
public static DataTable InnerJoin
(DataTable dt1, DataTable dt2,DataColumn Parent,DataColumn Child)
{
DataTable result = new DataTable();
var query =
from d in dt1.AsEnumerable()
join c in dt2.AsEnumerable() on d[Parent] equals c[Child]
select new { d, c };
/*
var columns = from d in dt1.Columns.Cast<DataColumn>()
from c in dt2.Columns.Cast<DataColumn>()
select new{c,d}
foreach (var column in columns)
{
result.Columns.Add(column);
}
**/
foreach (var row in query)
{
result.Rows.Add(row);
}
return result;
}
Your code compiles since there’s an overload which takes a
params object[]. But then you need to add two columns with typeDataRow.If that’s what you need, it should work.
Edit: and here’s a (working) test