以数字方式对字符串列表进行排序(1,2,...,9,10 而不是 1,10,2)

编程入门 行业动态 更新时间:2024-10-25 06:27:15
本文介绍了以数字方式对字符串列表进行排序(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?

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

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)

本文发布于:2023-06-08 21:25:19,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/589326.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   而不是   方式   数字   列表

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!