So the issue that I ran into recently is that I’m getting data in an observable object list and then getting an updated list. I need to be able to compare each object in the list to see if it has been updated or not. The problem is that I have a lot of properties in each object and I had several object lists which I needed to compare. The solution I wanted involves IComparable. This is a very simple interface that implements CompareTo method only. CompareTo receives an object and returns an integer. This interface is used for comparing and doing things like sorting in arrays but in this case all I need to check for is if the CompareTo returns 0 (equals) or anything but 0 (not equal).
Another problem is that to implement this function you have to write all the checking code yourself and if you have alot of properties to check you have to do that manually somehow. I wanted something to simply check to see if all properties in the current object and the object passed in through CompareTo function were equal. Here is some code to do that:
// Implement IComparable interface and use this as your function #region IComparable Members public int CompareTo(object obj) { int return_value = 0; if (obj.GetType() == this.GetType()) { Type t = this.GetType(); foreach (PropertyInfo p in t.GetProperties()) { Type t2 = obj.GetType(); object prop1_value = p.GetValue(this, null); object prop1_name = p.Name; foreach (PropertyInfo p2 in t2.GetProperties()) { object prop2_value = p2.GetValue(obj, null); object prop2_name = p2.Name; if (prop1_name == prop2_name) { if (prop1_value != null && prop2_value != null) { if (!prop1_value.Equals(prop2_value)) { return_value++; } } break; } } } } else { return_value++; } return return_value; } #endregion
This uses system.reflection to iterate through the properties in both objects comparing the values using the ‘Equals’ method to validate the values are the same. If the properties are not the same the return_value is incremented and more than 0 is returned. This is pretty generic and should work with most classes you build. You may need to add in an if statement to filter out properties you do not wish to include in this comparison as this just checks all properties in the object.
