排序字符串数 [英] sort string-numbers
问题描述
可能重复:
C#中的自然排序顺序
Possible Duplicate:
Natural Sort Order in C#
我有一个列表,里面有很多数字. 但是由于一些其他字母,它们被另存为字符串.
I have a list with a lot of numbers in it. But they are saved as strings because of some additional letters.
我的列表看起来像这样:
My list looks something like this:
1
10
11
11a
11b
12
2
20
21a
21c
A1
A2
...
但它应该看起来像这样
1
2
10
11a
11b
...
A1
A2
...
我如何对列表进行排序以获得此结果?
How do i sort my list to get this result?
推荐答案
按照前面的评论,我还将实现一个自定义的IComparer<T>
类.据我所知,项目的结构既可以是数字,也可以是数字的组合,后跟字母.在这种情况下,下面的IComparer<T>
实现应该可以工作.
Going by the previous comments, I would also implement a custom IComparer<T>
class. From what I can gather, the structure of the items is either a number, of a combination of a number followed by a letter(s). If this is the case, the following IComparer<T>
implementation should work.
public class CustomComparer : IComparer<string>
{
public int Compare(string x, string y)
{
var regex = new Regex("^(d+)");
// run the regex on both strings
var xRegexResult = regex.Match(x);
var yRegexResult = regex.Match(y);
// check if they are both numbers
if (xRegexResult.Success && yRegexResult.Success)
{
return int.Parse(xRegexResult.Groups[1].Value).CompareTo(int.Parse(yRegexResult.Groups[1].Value));
}
// otherwise return as string comparison
return x.CompareTo(y);
}
}
使用此IComparer<T>
,您可以通过执行以下操作对string
列表进行排序
With this IComparer<T>
, you'll be able to sort your list of string
by doing
var myComparer = new CustomComparer();
myListOfStrings.Sort(myComparer);
已对以下项目进行了测试:
This has been tested with the following items:
2, 1, 4d, 4e, 4c, 4a, 4b, A1, 20, B2, A2, a3, 5, 6, 4f, 1a
并给出结果:
1, 1a, 2, 20, 4a, 4b, 4c, 4d, 4e, 4f, 5, 6, A1, A2, a3, B2
这篇关于排序字符串数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!