How to get only the different fields
I have two objects of a class.
I need to compare each field with the other, and if the data is different to make certain actions
class A
{
int id;
string text;
public int Id
{
get { return id; }
}
public string Text
{
get { return text; }
}
}
as I see it:
Dictionary<string, string> list = aObj.different(bObj);
list.Key - name property
list.Value - val开发者_StackOverflowue of the bObj if it is different
public Dictionary<string, object> GetDifferences(A target)
{
Dictionary<string, object> differences = new Dictionary<string, object>();
foreach (PropertyInfo pi in typeof(A).GetProperties())
{
if (!pi.GetValue(this, null).Equals(pi.GetValue(target, null)))
differences.Add(pi.Name, pi.GetValue(target, null));
}
return differences;
}
I would probably write a helper that uses reflection to get the properties of both objects, loops through them and compares the values 1 to 1.
This might help you
And this one too
edit
i think it'd be easier if both your objects implemented the same interface too.
Make Class A : IComparable and define the logic for CompareTo()
Then you can use A.CompareTo. The benefit is you can then use this in List<> if you need to sort.
You can do this in a lot of different manners. The best one deppends of the length of your lists of attributes. The simplest way is iterate over a first list, and for each item, iterate over the second one and try to identify if they are differents.
For large lists (>20), with similar sizes (+/- 20%) you should sort the two lists, iterate over both identifying matching items.
For large lists with discrepant lengths you can build a dictionary with the larger list, iterating over the smaller looking for the matching item on the previous built dictionary.
精彩评论