C# DataRow 比較

衣舞晨風發表於2015-10-09
  /// <summary>
        /// dataRow比較
        /// </summary>
        /// <param name="drA"></param>
        /// <param name="drB"></param>
        /// <param name="columnNames">需要比較的列名稱</param>
        /// <returns></returns>
        public static bool DataRowCompare(DataRow drA, DataRow drB, string[] columnNames)
        {
            bool flag = false;
            //DataRow 中需要比較的列排序
            ColumnSort(drA, columnNames);
            ColumnSort(drB, columnNames);
            foreach (DataColumn dcA in drA.Table.Columns)
            {
                if (columnNames.Contains(dcA.ColumnName))
                {
                    foreach (DataColumn dcB in drB.Table.Columns)
                    {
                        if (columnNames.Contains(dcB.ColumnName))
                        {
                            if (dcB.ColumnName == dcA.ColumnName)//列名比較
                            {
                                //型別比較
                                if (dcB.DataType != dcA.DataType)
                                {
                                    flag = false;
                                    break;
                                }
                                //值比較
                                else if (CompareObject(drA[dcB.ColumnName], drB[dcB.ColumnName]))
                                {
                                    flag = true;
                                    break;
                                }
                            }
                        }
                    }
                }
            }
            return flag;
        }
		     /// <summary>
        /// 按照陣列中列名順序排序
        /// </summary>
        /// <param name="drA"></param>
        /// <param name="columnNames">按照陣列中列名順序排序</param>
        public static void ColumnSort(DataRow drA, string[] columnNames)
        {
            //drA 排序
            int i = 0;
            foreach (string columnName in columnNames)
            {
                if (drA.Table.Columns.Contains(columnName))
                {
                    drA.Table.Columns[columnName].SetOrdinal(i);
                    i++;
                }
            }
        }


物件比較方法 CompareObject(object objA, object objB):

 C# 物件比較(值型別、引用型別)


深拷貝部分程式碼:

C# 實體類序列化與反序列化一 (XmlSerializer)


C# 實體類序列化與反序列化二 (DataContractSerializer)



相關文章