Question
Compare two Lists for differences
I would like some feedback on how we can best write a generic function that will enable two Lists to be compared. The Lists contain class objects and we would like to iterate through one list, looking for the same item in a second List and report any differences.
We already have a method to compare classes, so we need feedback on how we can feed the method (shown below) from two Lists.
For example, say we have a simple "Employee" class that has three properties, Name, ID, Department. We want to report the differences between List and another List.
Note:
Both lists will always contain the same number of items.
As mentioned above, we have a generic method that we use to compare two classes, how can we incorporate this method to cater for Lists, i.e. from another method, loop through the List and feed the classes to the generic method .... but how do we find the equivalent class in the second List to pass to the method below;
public static string CompareTwoClass_ReturnDifferences<T1, T2>(T1 Orig, T2 Dest)
where T1 : class
where T2 : class
{
// Instantiate if necessary
if (Dest == null) throw new ArgumentNullException("Dest", "Destination class must first be instantiated.");
var Differences = CoreFormat.StringNoCharacters;
// Loop through each property in the destination
foreach (var DestProp in Dest.GetType().GetProperties())
{
// Find the matching property in the Orig class and compare
foreach (var OrigProp in Orig.GetType().GetProperties())
{
if (OrigProp.Name != DestProp.Name || OrigProp.PropertyType != DestProp.PropertyType) continue;
if (OrigProp.GetValue(Orig, null).ToString() != DestProp.GetValue(Dest, null).ToString())
Differences = Differences == CoreFormat.StringNoCharacters
? string.Format("{0}: {1} -> {2}", OrigProp.Name,
OrigProp.GetValue(Orig, null),
DestProp.GetValue(Dest, null))
: string.Format("{0} {1}{2}: {3} -> {4}", Differences,
Environment.NewLine,
OrigProp.Name,
OrigProp.GetValue(Orig, null),
DestProp.GetValue(Dest, null));
}
}
return Differences;
}
Any suggestions or ideas appreciated?
Edit: Targeting .NET 2.0 so LINQ is out of the question.