有SortDescription排序不同的字符串 [英] Have SortDescription sort strings differently

查看:1383
本文介绍了有SortDescription排序不同的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下字符串:

字符串1

字符串2

字符串3

字符串15

字符串17

我要的字符串进行排序如上。然而,当我使用SortDescription排序我的名单,我得到以下的输出:

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

字符串1

字符串15

字符串17

字符串2

字符串3

我知道有算法来做到这一点,但是有没有办法用内置的功能来做到这一点SortDescription?

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在我看来模型的属性的属性名称表示列我想进行排序。

sortby is the property name of the property in my view model that represents the column I want to be sorted.

好像我只有两个排序选项升序和降序。但是,它的方式排序的CollectionView不,我想我的字符串进行排序的方式。有没有一种简单的方法来解决这个问题。

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?

推荐答案

想通了感谢链接: /stackoverflow.com/questions/248603/natural-sort-order-in-c-sharp/248613#248613\">Natural排序

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();
    }

这篇关于有SortDescription排序不同的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆