How to union two data tables and order the result

16,119

Solution 1

var dt1 = new DataTable(); // Replace with Dt1
var dt2 = new DataTable(); // Replace with Dt2

var result = dt1.AsEnumerable()
            .Union(dt2.AsEnumerable())
            .OrderBy (d => d.Field<string>("emp_name"));

Solution 2

i think this code will help u to do it without using entity...

Dt1.Merge(Dt2);
Share:
16,119

Related videos on Youtube

Anyname Donotcare
Author by

Anyname Donotcare

Updated on June 04, 2022

Comments

  • Anyname Donotcare
    Anyname Donotcare almost 2 years

    Q: If I have two DataTables like this :

    Dt1(emp_num,emp_name,type)

    Dt2(emp_num,emp_name,type)

    I wanna to Union them and order the result by emp_name.

  • wcm
    wcm over 9 years
    Great answer, you helped me a lot (+1) but it's missing one thing. If you want the result to be a DataTable: retium result.CopyToDataTable();
  • Razor
    Razor over 9 years
    That's because it's missing that requirement in the question.
  • Malcolm Salvador
    Malcolm Salvador about 7 years
    question : is this UNION distinct? if it is not, how can I make rows DISTINCT?
  • Razor
    Razor about 7 years
    Distinct is a separate operation. To do this you can use the .Distinct() extension method.
  • Tushar R.
    Tushar R. over 3 years
    It works as expected. If you don't set any primary key on base table (in above example, Dt1), then merge works like 'UNION ALL'. It means if there are rows with same column values in base table and table to be merged, then both rows will be present in base table after merge. But if primary key is set on base table, then only those rows which don't exist in the base table as per the primary key, will be added in base table. Hence, no duplicates if primary key is set on base table.