Archive

Archive for June, 2015

Compare two object and get changes made in their values

Here we can compare values of a DataRow of DataTable or compare two object of same class. It will return you name of properties with differance in string.

string GetUpdatedHistory(DataRow orignalRecord, DataRow updatedRecord)
{
if (orignalRecord.Table.Columns.Count != updatedRecord.Table.Columns.Count)
{
return string.Empty;
}
StringBuilder text = new StringBuilder();
for (int i = 0; i < orignalRecord.Table.Columns.Count; i++)
{
if (Convert.ToString(orignalRecord[i]) != Convert.ToString(updatedRecord[i]))
{
text.Append("Column " + orignalRecord.Table.Columns[i].ColumnName +
string.Format(" changed from to ,”, Convert.ToString(orignalRecord[i]), Convert.ToString(updatedRecord[i])));
}
}
return text.ToString().Substring(0, text.ToString().Length – 1);
}
string GetUpdatedHistory(object type1, object type2)
{
StringBuilder text = new StringBuilder();
PropertyInfo[] instance1 = type1.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
PropertyInfo[] instance2 = type2.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
// Display information for all properties.
foreach (var propInfo in instance1)
{
PropertyInfo propInfo2 = (PropertyInfo)instance2.Where(x => x.Name == propInfo.Name).FirstOrDefault();
string value1 = Convert.ToString(propInfo.GetValue(type1, null));
string value2 = Convert.ToString(propInfo2.GetValue(type2, null));
if (value1 != value2)
{
text.Append(“Property ” + propInfo.Name +
string.Format(” changed from to ,”, Convert.ToString(value1), Convert.ToString(value2)));
}
}
return text.ToString().Substring(0, text.ToString().Length – 1);
}

Categories: .Net, C#