Mic*_*tum 16 .net c# sorting numbers
我有一个像这样的列表:
var l = new List<string> {"bla 1.txt","bla 2.txt","bla 10.txt","bla 3.txt"};
Run Code Online (Sandbox Code Playgroud)
如果我调用l.Sort(),列表将以1,10,2,3的顺序排序,这从纯字符串的角度来看是有意义的,但是从用户角度来看很糟糕.
因为我不想/不能强迫我的用户将它们命名为01,02,03,...我想知道是否有内置方法或简单算法来正确检测和排序数字,以便我有1,2,3,10?由于数字只有1或2个字符长(即不超过99),我可以做一个正则表达式,暂时为所有1位数字加前缀0和排序,但在重新发明轮子之前,我想知道是否已存在某些内容?
.net 3.5SP1如果重要,不是4.0
Dan*_*Tao 10
为什么不写一些会从字符串中提取数字的东西,像这样?
// Note: This could very well be a bad implementation. I'm not too great with Regex.
static int ExtractNumber(string text)
{
Match match = Regex.Match(text, @"(\d+)");
if (match == null)
{
return 0;
}
int value;
if (!int.TryParse(match.Value, out value))
{
return 0;
}
return value;
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以使用以下方式对列表进
list.Sort((x, y) => ExtractNumber(x).CompareTo(ExtractNumber(y)));
Run Code Online (Sandbox Code Playgroud)
这对我来说效率很低,但它至少应该起作用.
| 归档时间: |
|
| 查看次数: |
26798 次 |
| 最近记录: |