Introducing Radical.sh

Forget Code launches a powerful code generator for building API's

Comparing two datatables and performing MINUS operation using LINQ in C#

You can perform minus operation between two datatables as you do in RDBMS.

  1. using System.Linq;

  1. public DataTable getLinq(DataTable dt1, DataTable dt2)
  2. {
  3. DataTable dtMerged =
  4. (from a in dt1.AsEnumerable()
  5. join b in dt2.AsEnumerable()
  6. on
  7. a["Query"].ToString() equals b["Query"].ToString()
  8. into g
  9. where g.Count() ==0
  10. select a).CopyToDataTable();
  11. return dtMerged;
  12. }


Working example:

Consider datatable dt1 is having the data
Placeidtime
Russia122:10
Italy223:10
Australia200:10
India101:10
Pakistan602:10
Sri lanka103:10
China404:10
London105:10
Germany606:10
Iraq107:10
America408:10
India109:10

Consider datatable dt2 is having the data
Place
India
Iraq
Italy


Now we are going to perform MINUS operation. We are going to retrieve the rows from dt1 by neglecting the places from dt2.

  1. public DataTable getLinq(DataTable dt1, DataTable dt2)
  2. {
  3. DataTable dtMerged = (from a in dt1.AsEnumerable()
  4. join b in dt2.AsEnumerable()
  5. on a["Place"].ToString() equals b["Place"].ToString()
  6. into g
  7. where g.Count() == 0
  8. select a).CopyToDataTable();
  9.  
  10. return dtMerged;
  11. }


Result set :
Placeidtime
Russia130-12-1899 22:10
Australia201-01-1900 00:10
Pakistan601-01-1900 02:10
Sri lanka101-01-1900 03:10
China401-01-1900 04:10
London101-01-1900 05:10
Germany601-01-1900 06:10
America401-01-1900 08:10