Reputation: 2887
I have the following class and I've two object of it,Obj1 one have the previous data and obj2 have the data with some fields that can be changed (Im in action of edit which have obj1 before changing and obj2 after).my question is if I have the two object how is the best way to put in object (like list of key val) just the fields that was changed and they value. I read about it in the SO and I found this two approach but some of the post are old..., what is right/efficient way to go ?example will be very helpful.
Get the changed properties in same object
public class UserData
{
public int Id { get; set; }
public string UserName { get; set; }
public string Address { get; set; }
public string Email { get; set; }
public string Work { get; set; }
public string Home { get; set; }
}
public class Program
{
public static void Main()
{
UserData obj1 = new UserData();
obj1.Email = "www.test.com";
obj1.Home = "test home";
UserData obj2 = new UserData();
obj2.Email = "www.test2.com";
obj2.Home = "test home2";
}
}
I've tried like the following from this post but I got error,any idea? Compare two objects and find the differences
changedList = obj1.DetailedCompare(obj2);
I got this error,any idea how to solve it:
The type arguments for method
'Web.Controllers.extentions.DetailedCompare<T>(T, T)'
cannot be inferred from the usage. Try specifying the type arguments explicitly
Upvotes: 0
Views: 1674
Reputation: 1631
You have to create function which list and compare all properties of the two objects. This can be done by reflection :
public class UserData
{
public int Id { get; set; }
public string UserName { get; set; }
public string Address { get; set; }
public string Email { get; set; }
public string Work { get; set; }
public string Home { get; set; }
public IEnumerable<PropertyInfo> GetVariance(UserData user)
{
foreach (PropertyInfo pi in user.GetType().GetProperties()) {
object valueUser = typeof(UserData).GetProperty (pi.Name).GetValue (user);
object valueThis = typeof(UserData).GetProperty (pi.Name).GetValue (this);
if (valueUser != null && !valueUser.Equals(valueThis))
yield return pi;
}
}
}
I use the "Equals method" to compare the values of strings, int, etc and not their references contrary to an "==" (which compare reference here, because we get an object type).
UserData obj1 = new UserData();
obj1.Email = "www.test.com";
obj1.Home = "test home";
UserData obj2 = new UserData();
obj2.Email = "www.test2.com";
obj2.Home = "test home2";
IEnumerable<PropertyInfo> variances = obj1.GetVariance (obj2);
foreach (PropertyInfo pi in variances)
Console.WriteLine (pi.Name);
Caution, it work only with primitive's types (int, string, float, ...) because Equals compare the references of two object.
Upvotes: 2