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.

 
'==' 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



Below are tested methods to  check, are  DataTables or DataSets the same
/// <summary>
        /// 
        /// </summary>
        /// <param name="tbl1"></param>
        /// <param name="tbl2"></param>
        /// <returns></returns>
         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;
        }
       /// <summary>
        /// Compare content of all rows in the table.
        /// </summary>
        /// <param name="ds1"> The DS1.</param>
        /// <param name="ds2"> The DS2.</param>
        /// <returns></returns>
        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;
        }
posted @ Tuesday, August 27, 2013 9:49 PM
Print

Comments on this entry:

No comments posted yet.

Your comment:



(not displayed)

 
 
 
 
 

Live Comment Preview:

 
«September»
SunMonTueWedThuFriSat
31123456
78910111213
14151617181920
21222324252627
2829301234
567891011