Friday, August 07, 2015

DataTable row compare in C#

Here is the simple workaround to find the unique record from the source.
You must have two equal IEnumerable collection.

In Linq,we can use the "Except" method

In this example, I have 2 sample xml file that contains the records of books details such as book name,author and id.

In second XML has one new record, and wanted to output the new record in grid.

           DataSet ds = new DataSet();
            DataSet ds1 = new DataSet();
            ds.ReadXml(@"D:\Books.xml");


            bookgrd.DataSource = ds.Tables[0];
            bookgrd.DataBind();

            IEnumerable tbl1row = ds.Tables[0].AsEnumerable();
            ds1.ReadXml(@"D:\Books2.xml");


            
            IEnumerable tbl2row = ds1.Tables[0].AsEnumerable();
            GridView1.DataSource = ds1.Tables[0];
            GridView1.DataBind();
           
            var items = tbl2row.AsEnumerable().Select(r => r.Field("id"))
           .Except(tbl1row.AsEnumerable().Select(r => r.Field("id")));



            DataTable uniqueRow = (from row in tbl2row.AsEnumerable()
                                join id in items
                                on row.Field("id") equals id
                                select row).CopyToDataTable();

            GridView2.DataSource = uniqueRow;
            GridView2.DataBind();