1

I am trying to find the difference between two datatables based on a given column name. I cannot see what I am doing wrong here but when I pass two datatables that are different, I get no result.

    dt1                  dt2
ID    Percent        ID    Percent
---   -------        ---   -------
1     100            1     100
2     100            2     100
..    ...            ..    ...
50    0              50    20
..    ...            ..    ...

so, I call GetTableDiff(dt1, dt2, "Percent") and rather than getting one row (ID: 50, Percent: 20), I get nothing.

public static DataTable GetTableDiff(DataTable dt1, DataTable dt2, string sColumn)
{     
    DataTable dtDiff = new DataTable();
    try
    {
        var diff = from r1 in dt1.AsEnumerable()
                    join r2 in dt2.AsEnumerable()
                        on r1.Field<int>(sColumn)
                        equals r2.Field<int>(sColumn) into g
                    where !g.Any() // get only rows which do not have joined rows from dt2
                    select r1;

        if (diff.Count() > 0)
            dtDiff = diff.CopyToDataTable();
    }
    catch (Exception ex)
    {
    }
    return dtDiff;
}
3
  • Which column are joining on? Is sColumn the ID column in your example? If so, your example shows no rows which would not join. Commented Sep 28, 2018 at 12:25
  • 1
    Your rows will be joined anyway, you need to check whether Percent column's values are the same or not. Commented Sep 28, 2018 at 12:25
  • This will not produce a g if the columns don't match. All returned g's have g.Any() == true. Commented Sep 28, 2018 at 12:36

1 Answer 1

3

You need to join on "ID" instead of sColumn string, then compare your expect column name.

from r1 in dt1.AsEnumerable()
                join r2 in dt2.AsEnumerable()
                    on r1.Field<int>("ID")
                    equals r2.Field<int>("ID") 
                where r2.Field<int>(sColumn) != r1.Field<int>(sColumn) 
                select r1;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.