1

I have a listbox which has a sort like this:

ListBox.Items.SortDescriptions.Add(new SortDescription("Order", ListSortDirection.Descending));

But it sorts alphabetically, not numeric values! How to do that?

By the way - the property (aka column) is stored as a varchar in the database and the property is a string. But somehow I would like to convert it to a integer. And I tried with a another property and it was an integer and I couldn't sort it at all! It threw an exception!

marko
  • 10,684
  • 17
  • 71
  • 92

1 Answers1

3

If this is all the sorting you are going to be doing inside that control, a good option would be to set ListCollectionView.CustomSort to an IComparer instance that does natural sorting. This will couple the implementation to the type of the items in your ListView, but if that type is not going to change very often this is a reasonable limitation. On the other hand, the sort will be much faster because it won't need to involve reflection.

Assuming you have such a comparer:

var comparer = new ...

then all you need to do is install it:

var view = (ListCollectionView)
           CollectionViewSource.GetDefaultView(ListBox.ItemsSource);
view.CustomSort = comparer;

That's easy. So now we only have to find out what comparer looks like... Here's a very good answer showing how to implement such a comparer:

[SuppressUnmanagedCodeSecurity]
internal static class SafeNativeMethods
{
    [DllImport("shlwapi.dll", CharSet = CharSet.Unicode)]
    public static extern int StrCmpLogicalW(string psz1, string psz2);
}

public sealed class NaturalOrderComparer : IComparer
{
    public int Compare(object a, object b)
    {
        // replace DataItem with the actual class of the items in the ListView
        var lhs = (DataItem)a;
        var rhs = (DataItem)b;
        return SafeNativeMethods.StrCmpLogicalW(lhs.Order, rhs.Order);
    }
}

So, given the comparer above you should find everything working with

var view = (ListCollectionView)
           CollectionViewSource.GetDefaultView(ListBox.ItemsSource);
view.CustomSort = new NaturalOrderComparer();
Community
  • 1
  • 1
Jon
  • 428,835
  • 81
  • 738
  • 806