var collection = from t1 in dt1.AsEnumerable()
join t2 in dt2.AsEnumerable()
on t1["id"] equals t2["id"]
select new { Name = t1["name"], Group = t2["group"] };
Run Code Online (Sandbox Code Playgroud)
我想选择两个表的所有列,如 SQL Server 内部连接查询中的连接。
另外如何将两个表的整个结果转换为数据表?
var collection = from t1 in dt1.AsEnumerable()
join t2 in dt2.AsEnumerable()
on t1["id"] equals t2["id"]
select new { T1 = t1, T2 = t2 };
Run Code Online (Sandbox Code Playgroud)
然后...
编辑:
沿着这些路线的东西
//clone dt1, copies all the columns to newTable
DataTable newTable = dt1.Clone();
//copies all the columns from dt2 to newTable
foreach(var c in dt2.Columns)
newTable.Columns.Add(c);
//now newTable has all the columns from the original tables combined
//iterates over collection
foreach (var item in collection) {
//creates newRow from newTable
DataRow newRow = newTable.NewRow();
//iterate the columns, gets values from either original table if column name is there
foreach(var c in newTable.Columns)
newRow[c.ColumnName] = item.T1.ContainsColumn(c.ColumnName) ? item.T1[c.ColumnName] : item.T2[c.ColumnName];
newTable.Rows.Add(newRow);
}
Run Code Online (Sandbox Code Playgroud)
这将起作用。但是如果 dt1 和 dt2 共享多个具有完全相同名称的列,您可能会丢失一些数据。