Sort by row sort order differently

I have the following lines:

"Line 1"

"String 2"

"String 3"

"String 15"

"Line 17"

I want the rows to be sorted as above. However, when I use SortDescription to sort my list, I get the following output:

"Line 1"

"String 15"

"Line 17"

"String 2"

"String 3"

I understand that there are algorithms for this, however, is there a way to do this with the built-in SortDescription functions?

private void SortCol(string sortBy, ListSortDirection direction) { ICollectionView dataView = CollectionViewSource.GetDefaultView(ListView.ItemsSource); dataView.SortDescriptions.Clear(); SortDescription sd = new SortDescription(sortBy, direction); dataView.SortDescriptions.Add(sd); dataView.Refresh(); } 

sortby is the name of the property property in my view model, which represents the column that I want to sort.

It seems that I have only two sorting options: Ascending and Descending. But the CollectionView sorting method is not the way I would like my rows to be sorted. Is there an easy way to solve this problem?

+4
source share
2 answers

Found this out thanks to the link: Natural sort order in C #

 [SuppressUnmanagedCodeSecurity] internal static class SafeNativeMethods { [DllImport("shlwapi.dll", CharSet = CharSet.Unicode)] public static extern int StrCmpLogicalW(string psz1, string psz2); } public sealed class NaturalStringComparer : IComparer<string> { public int Compare(object a, object b) { var lhs = (MultiItem)a; var rhs = (MultiItem)b; //APPLY ALGORITHM LOGIC HERE return SafeNativeMethods.StrCmpLogicalW(lhs.SiteName, rhs.SiteName); } } 

And here is how I use the above comparison algorithm:

  private void SortCol() { var dataView = (ListCollectionView)CollectionViewSource.GetDefaultView(ListViewMultiSites.ItemsSource); dataView.CustomSort = new NaturalOrderComparer(); dataView.Refresh(); } 
+4
source

You can use linq

 var list = new List<string> { "String 1", "String 17", "String 2", "String 15", "String 3gg" }; var sort = list.OrderBy(s => int.Parse(new string(s.SkipWhile(c => !char.IsNumber(c)).TakeWhile(c => char.IsNumber(c)).ToArray()))); 

Return:

  "String 1", "String 2", "String 3gg" "String 15", "String 17", 
+1
source

All Articles