Merge two DataTables to Single DataTable using LIN

2020-03-31 09:34发布

问题:

ASP.NET using C#.NET; .NET3.5

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

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

EDIT:

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 { .... };

回答1:

try this

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"],
                  };

Edit

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;
                });


回答2:

I believe you can do something like this:

IEnumerable<DataRow> res = 
    from d1 in DataTable1.AsEnumerable()
    join d2 in DataTable2.AsEnumerable() on d1["Location"] equals d2["Location"]
    select new DataRow
    {
        d1["Location"],
        d1["Visa_Q1"],
        d1["Visa_Q2"],
        d2["Visa_Q3"],
        d2["Visa_Q4"]
    };

DataTable CombinedDataTable = res.CopyToDataTable<DataRow>();