Methods to verify, are DataTables or DataSets the same.

I wanted to verify, are DataTables in DataSets the same. I found a few similar implementations on StackOverflow, but the one that I've selected 

(http://stackoverflow.com/questions/7517968/how-to-compare-2-datatables/7518025%237518025) didn't work and returned unexpectedly false, when comparing two cells with the same values

          tbl1.Rows[i][c]     2     object {long}
          tbl2.Rows[i][c]     2     object {long}

          tbl1.Rows[i][c] == tbl2.Rows[i][c]     false     

I found, that it should be used Equals instead of ==.

          Equals(tbl1.Rows[i][c], tbl2.Rows[i][c])     true

There are a few articles, explaining the difference and reasons behind it.

Fromhttp://blogs.msdn.com/b/csharpfaq/archive/2004/03/29/when-should-i-use-and-when-should-i-use-equals.aspx

'==' Operators are overloaded, not overridden, which means that unless the compiler knows to call the more specific version, it'll just call the object version

See also http://blogs.msdn.com/b/ericlippert/archive/2009/04/09/double-your-dispatch-double-your-fun.aspx

Below are tested methods to  check, are  DataTables or DataSets the same

/// 

        /// 

        /// 

        /// 

        /// 

        /// 

         public static bool AreTablesTheSame( DataTable tbl1, DataTable tbl2)

        {

            if (tbl1.Rows.Count != tbl2.Rows.Count || tbl1.Columns.Count != tbl2.Columns.Count)

                return false;

            for ( int i = 0; i < tbl1.Rows.Count; i++)

            {

                for ( int c = 0; c < tbl1.Columns.Count; c++)

                {

                   if (!Equals(tbl1.Rows[i][c] ,tbl2.Rows[i][c]))

                        return false;

                }

            }

            return true;

        }

       /// 

        /// From http://stackoverflow.com/questions/7517968/how-to-compare-2-datatables/7518025#7518025

        /// Compare content of all rows in the table.

        /// 

        ///  The DS1.

        ///  The DS2.

        /// 

        public static bool  AreTablesTheSame( DataSet ds1, DataSet ds2)

        {

            if (ds1 == null && ds2 == null)

                return true;

            if (ds1 == null || ds2 == null) //only one is null

                return false;

            if (ds1.Tables.Count != ds2.Tables.Count)

                return false;

            for ( int i = 0; i < ds1.Tables.Count; i++)

            {

                if (! DataTableHelper.AreTablesTheSame(ds1.Tables[i] ,ds2.Tables[i]))

                    return false;

            }

            return true;

        }

This article is part of the GWB Archives. Original Author: Michael Freidgeim

New on Geeks with Blogs