以数字方式对字符串列表进行排序(1,2,...,9,10 而不是 1,10,2) [英] Sorting a List of Strings numerically (1,2,...,9,10 instead of 1,10,2)

查看:20
本文介绍了以数字方式对字符串列表进行排序(1,2,...,9,10 而不是 1,10,2)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的列表:

var l = new List<string> {"bla 1.txt","bla 2.txt","bla 10.txt","bla 3.txt"};

如果我调用 l.Sort(),列表将按 1、10、2、3 的顺序排序,这从纯字符串的角度来看是有意义的,但从用户的角度来看很糟糕.

If i call l.Sort(), the list gets sorted in the order 1,10,2,3 which makes sense from a pure string point of view, but sucks from a User Perspective.

由于我不想/不能强迫我的用户将它们命名为 01、02、03,...我想知道是否有内置方法或简单算法来正确检测和排序数字,所以我有1,2,3,10?由于数字只有 1 或 2 个字符长(即不超过 99),我可能会做一个正则表达式,临时用 0 前缀所有 1 位数字并排序,但在我重新发明轮子之前,我想知道是否已经存在?

Since I don't want to/can't force my users to name them 01, 02, 03,... I wonder if there is either a built-in method or simple algorithm to detect and sort numbers properly, so that I have 1,2,3,10? Since the numbers are only 1 or 2 characters long (i.e., no more than 99) I could possibly do a regex that temporarily prefixes all 1-digit numbers with a 0 and sort, but before I reinvent the wheel I wonder if something already exists?

.net 3.5SP1,如果重要的话,不是 4.0

.net 3.5SP1 if that matters, not 4.0

推荐答案

最好的方法是使用IComparer.这已经完成,可以在代码项目中找到.

The best approach is making use of IComparer. This has already been done and can be found on code project.

这篇关于以数字方式对字符串列表进行排序(1,2,...,9,10 而不是 1,10,2)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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