Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Have SortDescription sort strings differently [duplicate]

I have the following strings:

"String 1"

"String 2"

"String 3"

"String 15"

"String 17"

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

"String 1"

"String 15"

"String 17"

"String 2"

"String 3"

I understand there are algorithms to accomplish this, however is there a way to do this with the built in functionality of SortDescription?

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 property name of the property in my view model that represents the column I want to be sorted.

It seems like my only two sorting options are Ascending and Descending. But the way that it's sorts the CollectionView is not the way I would like my strings to be sorted. Is there an easy way to solve this?

like image 372
jsirr13 Avatar asked Mar 11 '13 22:03

jsirr13


1 Answers

Figured it 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's how I use the above algorithm comparer:

    private void SortCol()
    {
        var dataView =
                      (ListCollectionView)CollectionViewSource.GetDefaultView(ListViewMultiSites.ItemsSource);
        dataView.CustomSort = new NaturalOrderComparer();
        dataView.Refresh();
    }
like image 129
jsirr13 Avatar answered Sep 29 '22 15:09

jsirr13