Compare Two Objects of the Same Type and List Down the properties which are different.

Ndebata
Posted by Ndebata under C# category on | Points: 40 | Views : 2771
Compare Two Objects of the Same Type and List Down the properties which are different.

Here I have class as bellow

public class ClassA
{
public int ID { get; set; }
public string Name { get; set; }
public double Amount { get; set; }
public DateTime DOB { get; set; }
}

The following function retuns a string which describes a change in properties.

private static string CompareTwo(ClassA oldObj, ClassA newObj)
{
StringBuilder sb = new StringBuilder();
sb.Append("The Following feilds has been changed");
sb.AppendLine();
foreach (var item in oldObj.GetType().GetProperties())
{
if (newObj.GetType().GetProperties().Where(n => n.Name == item.Name && !n.GetValue(newObj, null).Equals(item.GetValue(oldObj, null))).Count() > 0)
{
sb.AppendLine();
sb.AppendFormat("{0}: From {1} to {2}",item.Name,item.GetValue(oldObj,null),newObj.GetType().GetProperties().FirstOrDefault(n => n.Name == item.Name).GetValue(newObj,null));
}
}
sb.AppendLine();
return sb.ToString();
}

The main method of console app can be written as

static void Main(string[] args)
{
ClassA oldclass = new ClassA { ID = 1, Amount = 2.5, Name = "Old", DOB = new DateTime(2010, 1, 1) };
ClassA newclass = new ClassA { ID = 1, Amount = 3.5, Name = "New", DOB = new DateTime(2010, 3, 3) };

Console.WriteLine(CompareTwo(oldclass, newclass));
}

Thanks,
Debata

Comments or Responses

Login to post response