The algorithm itself is normally used for strings, but there is nothing to prevent you from using it for a collection of anything. After all, a string is merely a collection of characters. I’ve modified the algorithm slightly to use a generic C# collection. Before showing you the code, it is probably useful to show you a simple unit test to show how the diff class can be used.
Of interest in this code are two custom classes, ComparisonResult and CollectionDiffer. The CollectionDiffer class is the class we are most interested in, but seeing that it will return us a collection of ComparisonResult objects, we should probably try to understand this class first. A ComparisonResult contains two fields, one being an enum of type ModificationType, and the other being a generic TypeParam property and represents the value of a portion of the comparison. If this is confusing, just try to grok what is being tested in the unit test.
For reference, the ModificationType and ComparisonResult types look like:
In the unit test you can see that we have two variables declared at the top of the test, baseline and revision. They are both collections of type int. You’ll notice that they are pretty similar in value. This is a pretty trivial example, and you are probably thinking “Why would I need an algorithm to tell me that the 2 has been deleted and the 4 and the 5 have been inserted?”. This is a valid point but only for trivial examples. The hairy thing about a diff algorithm is that without change tracking in place during the actual modifications, there is no way to actually know with 100% what has been deleted or inserted in certain scenarios. For instance, given the string “ABC”, and a revision “ACB”, either of the following scenarios could have happened:
B was deleted, and then inserted at the end.
C was deleted, and then inserted in the middle.
In fact, those two are just the most likely scenarios, but there are really an infinite number of ways to get from “ABC” to “ACB”.
The same ambiguity applies no matter the type. The point is, letting a proven algorithm decide what has been deleted and inserted will provide consistent results when they are needed. Using an integer for the TypeParam also isn’t all that exciting. You could just as easily make it a char, or a Guid, or anything you like.
Now for the actual C# implementation of a generic solution to the longest common subsequence problem. I’m telling you up front, it’s a little tricky, and this post isn’t about to go into how the LCS algorithm actually works. If you are looking for that information, I suggest wikipedia.