C# 用数字对数组列表进行排序
你好,我确实想要对一个数组进行排序,其中包含这个:
String[] info = new String[5]{"6,j", "7,d", "12,s", "4,h", "14,s" };
但是如果我使用这个:
Array.Sort(info);
输出变成:
"7,d"
"6,j"
"4,h"
"14,s"
"12,s"
但我不会输出是:
"14,s"
"12,s"
"7,d"
"6,j"
"4,h"
在/使用 C# 中执行此操作的最简单方法是什么?
当我这样做时,我无法让字母数字排序工作:
Array.Sort(info, new AlphanumComparatorFast());
找不到类型或命名空间“AlphanumComparatorFast” 您缺少 using 指令或程序集引用 ...
我得到的错误是
Hello i do want a sort an array, that contains this:
String[] info = new String[5]{"6,j", "7,d", "12,s", "4,h", "14,s" };
But if i use this:
Array.Sort(info);
The output becomes:
"7,d"
"6,j"
"4,h"
"14,s"
"12,s"
But i wont the output to be:
"14,s"
"12,s"
"7,d"
"6,j"
"4,h"
What is the easiest way to do it in/with C#??
And i cant get Alphanumeric sort to work when i do like this:
Array.Sort(info, new AlphanumComparatorFast());
the type or namespace "AlphanumComparatorFast" could not be found are
you missing a using directive or an assembly reference
is the error that i get...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
尝试:
这仅按数字部分排序,但您可以详细说明该示例。此代码强烈假设始终存在逗号分隔符,这可能是生产中的问题,请进行一些更准确的错误处理。
如果数组包含一些不符合异常的元素,只要可以忽略失败的元素,我们可以编写:
try with:
This sorts just by the numeric part, but you can elaborate on that sample. This code strongly assumes that there is always the comma separator, this may be is an issue in production, do some more accurate error handling.
Should the array contains some elements that does not conform the exception, providing that is acceptable to ignore the failing elements, we can write:
您可以解析它们并将它们分成一个类,而不是将它们表示为字符串。实施 IComparable 就可以了。双关语完全是有意的。
或者,实现您自己的排序比较器来解析对象,然后对它们进行正确排序。
Rather than represent these as strings, you could parse them and split them out into a class. Implement IComparable and you're sorted. Pun fully intended.
Or, implement your own sort comparator to parse the objects and then sort them correctly.
您可以使用自定义比较器
,并且可以像这样使用比较器
you can use a custom comparer
and you can use your comparer like so
如果您使用 .NET 2.0 并且无法使用 Linq,您可以尝试:
这假设分隔符始终是逗号,如果需要,请添加您自己的验证代码。
If you're using .NET 2.0 and unable to use Linq you can try:
This assumes the separator is always a comma, add your own validation code if needed.
这是我不久前写的一些代码,我确信有一种更有效的方法可以做到这一点,但这确实有效。
要使用它,包括:
然后调用 use a linq query:
当然包括相关方法:
Here is a bit of code I wrote a while ago, I'm sure there's a more efficient way to do it, but this certainly works.
To use it, include:
then call use a linq query:
and of course include the relevant method:
对字符串的数字部分进行排序:
Sorting on the numeric part of the string: