none
Linq Except Extension method for datatables difference RRS feed

  • Question

  • Hi All,

    Trying to use AsEnuberable().Except method to get difference of two tables but unable to get desired result.

    my 1st datatable has 10 cols and 2nd datatable has 6 cols. i need to compare only 3 common columns from both table. so in output only those rows from 1st table must come which are not in 2nd table( filtering condition is equality of three common columns only)

    i got some hint in below link but not proper as in below structure of both tables are same

    http://social.msdn.microsoft.com/Forums/en/adodotnetdataset/thread/e68e60c2-b33b-43d7-8efd-11d1a9618ed1?prof=required

    my comarer class is:

    public class CountryRowComparer : IEqualityComparer<DataRow>
           {
               public bool Equals(DataRow r1, DataRow r2)
               {
                   for (int i = 0; i < r1.Table.Columns.Count; i++)
                   {
                       if (r1["EON ID"].ToString() != r2["EON ID"].ToString() && r1["User ID"].ToString() != r2["User ID"].ToString() && r1["Database Full Name"].ToString() != r2["Database Full Name"].ToString())
                           {
                               return false;
                           }
                   }
                   return true;
               }

               public int GetHashCode(DataRow r)
               {
                   return r.ToString().GetHashCode();
               }
           }

    and trying to get desired output as

    IEnumerable<DataRow> idrP = dt1.AsEnumerable();
               IEnumerable<DataRow> idrS = dt2.AsEnumerable();

               IEnumerable<DataRow> Results = idrP.Except(idrS, new CountryRowComparer());
               dt = Results.CopyToDataTable();

    but i am getting all rows from table 1.

    Wednesday, October 31, 2012 1:33 PM

Answers

  • Hi Hitu,

    Welcome to the MSDN forum.

    Based on your EqualityComparer, the values of column “EON ID”, "User ID", and "Database Full Name" will be compared. If the different values exist (for example, Table idrP have a set of value (“EON ID”, "User ID", and "Database Full Name") that Table idrS have not a set which have the same values as it), this row will be returned. I am not sure if what you want is all three fields are not equal at the same time. I tested your code on my side, and it works correctly. Could you please try to use this in Equals method to check if the result is what you want:

    if (r1["EON ID"].ToString() != r2["EON ID"].ToString() || r1["User ID"].ToString() != r2["User ID"].ToString() || r1["Database Full 
    
    Name"].ToString() != r2["Database Full Name"].ToString())
    {
        return false;
    }
    else
    {
        return true;
    }

    Best Regards,


    Alexander Sun [MSFT]
    MSDN Community Support | Feedback to us

    • Marked as answer by hitu.kala Monday, November 5, 2012 7:35 AM
    Friday, November 2, 2012 9:26 AM