I would like some feedback on how best to write a generic function that allows you to compare two lists. Lists contain class objects, and we would like to iterate over one list, looking for the same element in the second list and report any differences.
We already have a method for comparing classes, so we need feedback on how we can submit a method (shown below) from two lists.
For example, let's say we have a simple class "Employee", which has three properties: name, identifier, department. We want to report the differences between a list and another list.
Note:
Both lists will always contain the same number of items.
As mentioned above, we have a general method that we use to compare two classes, how can we include this method for serving lists, i.e. from another method, iterate over the list and combine classes with a common method ... but how can we find the equivalent class in the second list to go to the next method:
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: Orientation is .NET 2.0, so LINQ is out of the question.