I have done some migrations in a project that already contained some real-world data or that had a follow-up (we have some corrections, could you run it again? Eh… no, it’s a migration functionality, I already told you it’s a synchronize-functionality you wanted)? And for my private backup script I needed to synchronize, so I developed (my version of) a solution to compare and synchronize lists of different datatypes.
The solution has the following steps:
- I get the source and the target data.
- convert them to an intermediate datatype. with the same key for identity
- Check the Delta:
- Get a list of deleted items: items in target, that are missing in source
- Get a list of new items: items in source, that are missing in target
- Get a list of items with specific differences in values.
- With this list, run some custom code to handle the Delta in the target data.
Now I’m slowly working to convert it to a generic tool. However, it’s a bit complex when comparing objects. It’s a story about references and value types, about boxing and unboxing. When I have some time I will try to explain it to myself in another article.
Do I Compare and why not?
One additional thing: the IComparable and the IComparer. Sounds usefull for comparing. However, but it’s purpose is mostly in context of a sorting a list. When comparing value A with B, is A greater than (1), equal to (0) or less than B – so you can use it to determine the order.
With the implementation of IComparable you will add the default sort order to an object, so you use that in an array or a list (like Array.Sort(objectArray)).
With IComparer you can add additional sorting order to an object (like Array.Sort(objectArray, object.additionalSortBy)).