Sorting a List of Strings numerically (1,2,...,9,10 instead of 1,10,2)(以数字方式对字符串列表进行排序(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)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:以数字方式对字符串列表进行排序(1,2,...,9,10 而不是 1,10,2)


基础教程推荐
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01