wpf 让 SortDescription 对字符串进行不同的排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15349844/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Have SortDescription sort strings differently
提问by jsirr13
I have the following strings:
我有以下字符串:
"String 1"
“字符串 1”
"String 2"
“字符串2”
"String 3"
“字符串 3”
"String 15"
“字符串 15”
"String 17"
“字符串 17”
I want the strings to be sorted as above. However, when I use SortDescription to sort my list, I get the following output:
我希望字符串按上述方式排序。但是,当我使用 SortDescription 对我的列表进行排序时,我得到以下输出:
"String 1"
“字符串 1”
"String 15"
“字符串 15”
"String 17"
“字符串 17”
"String 2"
“字符串2”
"String 3"
“字符串 3”
I understand there are algorithms to accomplish this, however is there a way to do this with the built in functionality of SortDescription?
我知道有一些算法可以实现这一点,但是有没有办法使用 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.
sortby 是我的视图模型中属性的属性名称,它表示我想要排序的列。
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?
似乎我只有两个排序选项是升序和降序。但是它对 CollectionView 进行排序的方式并不是我希望对字符串进行排序的方式。有没有简单的方法来解决这个问题?
采纳答案by jsirr13
Figured it out thanks to the link: Natural Sort Order in C#
感谢链接: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();
}
回答by sa_ddam213
You could use Linq
你可以使用 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())));
Returns:
返回:
"String 1",
"String 2",
"String 3gg"
"String 15",
"String 17",

