How do I compare two datatables

Posted by cmrhema on Stack Overflow See other posts from Stack Overflow or by cmrhema
Published on 2011-01-15T07:58:40Z Indexed on 2011/01/16 14:53 UTC
Read the original article Hit count: 236

Filed under:

I have a datatable that will consist of 72 columns.

I will download it in the excel sheet using VSTO, which works fine.

Now the user will change either one of these rows or all of these rows and will also insert a fresh row.

Considering the datatable downloaded first to be dtA, and the one that has been modified in the excel sheet to be dtB.

I want to compare dtA and dtB.

I need to find out all the rows in dtB that do not exist in dtA.

I cant put foreach loop for each and every single row and evaluate as its a very untidy way of coding.

What is a better way to do this?

I did this way,

    DataTable dtA = new DataTable();
    dtA.Columns.Add("ENo");
    dtA.Columns.Add("ENo1");
    dtA.Columns.Add("ENo2");
    dtA.Columns.Add("ENo3");
    dtA.Columns.Add("ENo4");

    for (int i = 0; i < 5; i++)
    {
        DataRow dr = dtA.NewRow();
        dr[0] = "Part 0 " + i.ToString();
        dr[1] = "Part 1 " + i.ToString();
        dr[2] = "Part 2 " + i.ToString();
        dr[3] = "Part 3 " + i.ToString();
        dr[4] = "Part 4 " + i.ToString();
        dtA.Rows.Add(dr);
    }

    DataTable dtB = new DataTable();
    dtB.Columns.Add("ENo");
    dtB.Columns.Add("ENo1");
    dtB.Columns.Add("ENo2");
    dtB.Columns.Add("ENo3");
    dtB.Columns.Add("ENo4");

    for (int i = 5; i < 10; i++)
    {
        DataRow dr = dtB.NewRow();
        dr[0] = "Part 0 " + i.ToString();
        dr[1] = "Part 1 " + i.ToString();
        dr[2] = "Part 2 " + i.ToString();
        dr[3] = "Part 3 " + i.ToString();
        dr[4] = "Part 4 " + i.ToString();
        dtB.Rows.Add(dr);
    }

    Response.Write("\n");
    Response.Write("dt A");
    Response.Write("\n");

    for (int i = 0; i < dtA.Rows.Count; i++)
    {
        Response.Write(dtA.Rows[i][i].ToString());
        Response.Write("\n");
    }

    Response.Write("\n");
    Response.Write("dt B");
    Response.Write("\n");
    for (int i = 0; i < dtB.Rows.Count; i++)
    {
        Response.Write(dtB.Rows[i][i].ToString());
        Response.Write("\n");
    }

    var VarA = dtA.AsEnumerable();
    var varB = dtA.AsEnumerable();

    var diff = VarA.Except(varB);
    Response.Write("except");
    foreach (var n in diff)
    {
        Response.Write(n.Table.Rows[0].ToString());

    }

But I do not know what to use in the foreach var, What should I use pls?

© Stack Overflow or respective owner

Related posts about c#