i have what seems like a common problem / pattern. two collections of the same object. The object has a number of properties and some nested objects within it. Car has a property called id which is the unique identifier.
I want to find the LINQ way to do a diff, which includes:
- Items in one collection and not the other (visa versa)
- For the items that match, are there any changes (changes would be a comparison of all properties? (i only care about settable properties, would i use reflection for this ?? )
You can use the
Enumerable.Except()method. This uses a comparer (either a default or one you supply) to evaluate which objects are in both sequences or just one:If you want to perform a complete disjunction of both sequences
(A-B) union (B-A), you would have to use:If you have a complex type, you can write an
IComparer<T>for your type T and use the overload that accepts the comparer.For the second part of your question, you would need to roll your own implementation to report which properties of a type are different .. there’s nothing built into the .NET BCL directly. You have to decide what form this reporting would take? How would you identify and express differences in a complex type? You could certainly use reflection for this … but if you’re only dealing with a single type I would avoid that, and write a specialized differencing utility just for it. If yo’re going to support a borad range of types, then reflection may make more sense.