排序列表在 C# 中
如何根据项目的整数值对列表进行排序
该列表类似于
"1"
"5"
"3"
"6"
"11"
"9"
"NUM1"
"NUM0"
结果应该类似于 有
"1"
"3"
"5"
"6"
"9"
"11"
"NUM0"
"NUM1"
没有任何想法可以使用 LINQ 或 Lambda 表达式来执行此操作?
提前致谢
How to sort a List based on the item's integer value
The list is like
"1"
"5"
"3"
"6"
"11"
"9"
"NUM1"
"NUM0"
The result should be like
"1"
"3"
"5"
"6"
"9"
"11"
"NUM0"
"NUM1"
is there any idea to do this using LINQ or Lambda expression?
Thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
这称为“自然排序顺序”,通常用于对您拥有的项目(如文件名等)进行排序。
这是一个天真的(从某种意义上说,它可能存在很多 unicode 问题)实现似乎可以解决问题:
您可以将下面的代码复制到 LINQPad 来执行它并测试它。
基本上,比较算法将识别字符串内的数字,并通过用前导零填充最短的数字来处理这些数字,例如两个字符串
"Test123Abc"
和"Test7X"
应该像"Test123Abc"
和"Test007X"
一样进行比较,这应该会产生您想要的结果。然而,当我说“天真”时,我的意思是我可能在这里遇到大量真正的 unicode 问题,例如处理变音符号和多代码点字符。如果有人可以提供更好的实现,我很乐意看到它。
注意:
代码:
This is called a "natural sort order", and is usually employed to sort items like those you have, like filenames and such.
Here's a naive (in the sense that there are probably plenty of unicode-problems with it) implementation that seems to do the trick:
You can copy the code below into LINQPad to execute it and test it.
Basically the comparison algorithm will identify numbers inside the strings, and handle those by padding the shortest one with leading zeroes, so for instance the two strings
"Test123Abc"
and"Test7X"
should be compared as though they were"Test123Abc"
and"Test007X"
, which should produce what you want.However, when I said "naive", I mean that I probably have tons of real unicode problems in here, like handling diacritics and multi-codepoint characters. If anyone can give a better implementation I would love to see it.
Notes:
Code:
怎么样:
How about:
尝试编写一个小帮助器类来解析和表示您的标记。例如,没有太多检查:
现在编写比较器变得很容易,或者手动排序:
给出结果:
Try writing a small helper class to parse and represent your tokens. For example, without too many checks:
Now it becomes easy to write a comparer, or sort it manually:
Gives the result:
Jeff Atwood 有一篇博客文章 关于自然排序,他链接到所需算法的一些可用实现。
Jeffs 的一个链接指向 Dave Koelle 如何拥有 C# 实现:
Jeff Atwood has a blog post about natural sorting where he links to some available implementations of the desired algorithm.
One of Jeffs links points to Dave Koelle how has a C# implementation:
这是最快的算法 - 我花了 2 英里来排序 50 个项目
~~
This is the Fastest Algorithm - took me 2 mili to sort 50 items
~
~
这是一个 C# 7 解决方案(假设列表的名称为 a):
Here is a C# 7 solution (assuming the list has the name a):
我认为除了 listName.Sort() 之外你不需要任何东西,因为 sort() 方法使用默认比较器来快速排序节点。默认比较器正是您感兴趣的。
I don't think you need anything besides listName.Sort() because sort() method uses default comparer to quick sort nodes. Default comparer does exactly what you are interested in.