Reputation: 11393
Q:
I have two data tables and i wanna to inner join the and return the result in a another datatable through LINQ.
DataTable dt1 = StaffCVDAL.getCourses(int.Parse(Session["emp_num"].ToString()));
DataTable dt2 = cc1lectcrsfilesDAL.ListFiles(int.Parse(Session["emp_num"].ToString()), int.Parse(Session["permission_code"].ToString()));
DataTable dt = from t1 in dt1.AsEnumerable()
join t2 in dt2.AsEnumerable()
on t1["crsnum"] equals t2["crsnum"]
select new { t1["crsname"],t2["group"] }; //the problem is here .
Upvotes: 2
Views: 15279
Reputation: 30882
The problem is that the query expression (LINQ) returns an IEnumerable
of the anonymous type you created, instead of a DataTable
. IMHO, I prefer working with collections instead of datatables, but if you want to have a DataTable, you can create and populate it yourself from the collection, like this:
var collection = from t1 in dt1.AsEnumerable()
join t2 in dt2.AsEnumerable()
on t1["crsnum"] equals t2["crsnum"]
select new { Name = t1["crsname"], Group = t2["group"] };
DataTable result = new DataTable("NameGroups");
result.Columns.Add("crsname", typeof(string));
result.Columns.Add("group", typeof(int));
foreach (var item in collection)
{
result.Rows.Add(item.Name, item.Group);
}
for more details, and a more general solution, take a look at this.
Upvotes: 4