简体   繁体   中英

Merge two DataTables to Single DataTable using LINQ, C#

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM