How to sort by integer in list in WPF collection?

I have a list that looks like this:

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

But it is sorted alphabetically, not in numerical values! How to do it?

By the way, the property (aka column) is stored as varchar in the database, and the property is a string. But somehow I would like to convert it to an integer. And I tried with another property, and it was an integer, and I could not sort it at all! This is an exception!

0
source share
1 answer

If this is all the sorting you are going to do inside this control, a good option would be to set ListCollectionView.CustomSort to an IComparer instance that performs natural sorting. This will associate the implementation with the type of elements in your ListView , but if this type does not change very often, this is a reasonable limitation. Sorting, on the other hand, will be much faster because it does not need to include reflection.

Assuming you have a comparator like this:

 var comparer = new ... 

then all you have to do is install it:

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

It is easy. So, now we only need to find out what comparer looks like ... Here is a very good answer showing how to implement such a comparator:

 [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 comparative example above, you should find everything that works with

 var view = (ListCollectionView) CollectionViewSource.GetDefaultView(ListBox.ItemsSource); view.CustomSort = new NaturalOrderComparer(); 
+2
source

All Articles