I am writing a program that gets data from a database and compares it value-by-value to older data and then needs to be able to:
- Output the Old Data
- Output the New Data
- Output only the Differences
So, for simplicity's sake, suppose I created the following class to store the values:
class MyClass
{
// These fields will not be compared:
public string Id { get; set; }
public string Name { get; set; }
public string NONCompField1 { get; set; }
public int NONCompField2 { get; set; }
// These fields WILL be compared:
public string CompField1 { get; set; }
public int CompField2 { get; set; }
public int CompField3 { get; set; }
public double CompField4 { get; set; }
}
And, as the name suggests in my example, I want to compare the old and new values but only based upon the CompFields to find the differences.
I know I can hard-code a solution as follows:
public IEnumerable<Tuple<string, string, string>> GetDiffs(MyClass Other)
{
var RetVal = new List<Tuple<string, string, string>>();
if (CompField1 != Other.CompField1)
RetVal.Add(Tuple.Create("CompField1", CompField1, Other.CompField1));
if (CompField2 != Other.CompField2)
RetVal.Add(Tuple.Create("CompField2", CompField2.ToString(), Other.CompField2.ToString()));
if (CompField3 != Other.CompField3)
RetVal.Add(Tuple.Create("CompField3", CompField3.ToString(), Other.CompField3.ToString()));
if (CompField4 != Other.CompField4)
RetVal.Add(Tuple.Create("CompField4", CompField4.ToString(), Other.CompField4.ToString()));
return RetVal;
}
And that gives me back a Tuple<string, string, string> of (Field_Name, Current_Value, Old_Value) and that works just fine, but I'm looking for a nicer, mode dynamic way to do this that will allow for new fields being added in the future - whether they be CompareFields (need to update the GetDiffs) or NONCompFields (no need to update the GetDiffs).
My first thought would be to use DataAnnotations and then reflection to find fields with a specific attribute and loop through them for the GetDiffs method, but that seems like a cheat / bad way to do things.
Is there a better / more established way to do this that would minimize the need to update extra code?
Thanks!!!