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)
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 输入按键事件处理程序 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
