ASP.NET使用C#.NET; .NET3.5
ASP.NET using C#.NET; .NET3.5
我有两个DataTable如下:
I've two datatables as below:
DataTable1
Location Visa_Q1 Visa_Q2
Blore 25 40
Hyd 40 60
DataTable2
Location Visa_Q3 Visa_Q4
Blore 50 35
Hyd 80 90
如何到两个数据表结合起来,以获取数据表的输出如下使用 LINQ
(不包括循环的每一行):
How to combine both datatables for getting the output as DataTable as below using LINQ
(without looping each row):
CombinedDataTable
Location Visa_Q1 Visa_Q2 Visa_Q3 Visa_Q4
Blore 25 40 50 35
Hyd 40 60 80 90
修改
仅仅通过加入基于匹配的'位置',我想结合形式所产生的数据的两个表。我不想手动选择每一列字段作为选择新{...};
Just by joining two tables based on matching 'Location' i want the resultant data in combined form. I don't want to select each column field manually as select new { .... };
试试这个
var results = from table1 in dt1.AsEnumerable()
join table2 in dt2.AsEnumerable() on table1["Location"] equals table2["Location"]
select new
{
Location = table1["Location"],
Visa_Q1 = (int)table1["Visa_Q1"],
Visa_Q2 = (int)table1["Visa_Q2"],
Visa_Q3 = (int)table2["Visa_Q3"],
Visa_Q4 = (int)table2["Visa_Q4"],
};
修改
尝试一下本作选择所有列
try this for select all columns
DataTable table = new DataTable();
foreach (DataColumn column in t1.Columns)
{
table.Columns.Add(column.ColumnName, column.DataType);
}
foreach (DataColumn column in t2.Columns)
{
if (column.ColumnName == "Location")
table.Columns.Add(column.ColumnName + "2", column.DataType);
else
table.Columns.Add(column.ColumnName, column.DataType);
}
var results = t1.AsEnumerable().Join(t2.AsEnumerable(),
a => a.Field<String>("Location"),
b => b.Field<String>("Location"),
(a, b) =>
{
DataRow row = table.NewRow();
row.ItemArray = a.ItemArray.Concat(b.ItemArray).ToArray();
table.Rows.Add(row);
return row;
});