Wednesday, 19 March 2014

Generic collection synchronizer

This article demonstrates a generic way of the collections synchronization.  Why do we need that? Typically, in the programming we have one master collection and the slave collection.

The master collection usually represents the outcome of some process, whereas the slave collection is the graphical representation of the master collection.

Let us look at the simple example: our master collection is the set of the orders in the trading software. This set is always dynamic – the number and the content of the orders can change very quickly and we have to display these changes in the ListView.

There are a few ways of doing it; we clear the list and fill it with the items. Each update recreates a new list. Well, if you have only a few items, this will do. But even so you have to recreate the state of each item. If, for instance, the item was selected, you somehow have to select the item again. Which exactly item? We don’t know, we have to identify the item in the new collection.

The situation becomes even worse if the number of items exceeds hundreds and we have to recreate them from the scratch. Another more sensible approach implies the update of the individual items, if required adding new items and deleting the nonexistent ones.

The problem with the second approach is that the algorithm for doing this is not trivial with numerous iterations. It must be also fast.

The solution


We create the generic class for the synchronization and connect the target list with this object. The target can be anything – ListBox, ListView, TreeView,  basically any class that holds the collection of items.

Download Visual Studio Project that demonstrates BaseSyncronizer class.

No comments:

Post a Comment