Wednesday, October 15, 2014

Sorting ListCollectionView as Object Values Change

Recently, a new requirement popped up.  The requirement was to sort a list of objects in a data-grid, bound to a ListCollectionView as object values in the collection were changed.  In our case, the object type we wanted to sort on was a double.

At first I tried to implement this using a SortDescription, but I quickly realized this had one drawback.  The SortDirection seems to set an alphanumeric sort on the data column.  Values (1, 2, 10, 200, 100) would be sorted as (1, 10, 100, 2, 200) which was precisely not what I wanted.   To get a pure numeric sort it seemed I'd have to write my own logic. 

Thankfully the list collection view provides another property CustomSort, which takes an IComparer<T>.  The MSDN docs mention that it's preferred to derive from Comparer<T> instead of the interface.  With that in mind I was able to create the following class. 


This custom sorter was then wired into my ListCollectionView like so.
This provided the desired functionality of sorting each row into the correct position as the values were edited.
Row in edit mode is not sorted

Edit completed and row is sorted into place

While this worked great for what we were doing, I can't speak to how this would perform with extremely large sets of data.  

No comments:

Post a Comment