[英]how to sort an array of string containing numbers, numerically
So as the title already suggests I simply want to know if it is possible to sort elements that are in a string array via the numbers that are also contained within those strings.因此,正如标题已经暗示的那样,我只想知道是否可以通过也包含在这些字符串中的数字对字符串数组中的元素进行排序。
In my program I have been able to read the contents of a file which are laid out like this:在我的程序中,我已经能够读取文件的内容,这些文件的布局如下:
Adele got 2,Jack got 8
I have then been able to split this file via the comma into a string array called names:然后我就可以通过逗号将这个文件分割成一个名为 names 的字符串数组:
Dim fileReader As System.IO.StreamReader
Dim line As String
fileReader = My.Computer.FileSystem.OpenTextFileReader(ClassA)
line = fileReader.ReadLine
names = line.Split(",")
For Each element As String In names
Array.Sort(names)
Console.WriteLine(element)
Next
I was also able to sort the file alphabetically giving an output of:我还能够按字母顺序对文件进行排序,并给出以下输出:
Adele got 2
Jack got 8
However what I want to know is whether it is or isn't possible to sort these strings based on the number so the output would look like:但是我想知道的是是否可以根据数字对这些字符串进行排序,以便输出如下所示:
Jack got 8
Adele got 2
I also considered using regex to extract the numbers, parse them as integer, save them to a variable and then add them to an array and compare the arrays but their has to be a simpler way D:我还考虑使用正则表达式来提取数字,将它们解析为整数,将它们保存到一个变量中,然后将它们添加到一个数组中并比较这些数组,但它们必须是一种更简单的方法 D:
Any help is much appreciated guys :)任何帮助都非常感谢伙计们:)
Linq to the rescue.林克来救援。 I added to the data to be sure it would handle 2 digit numerals and because 2 elements is a feeble test:
我添加到数据中以确保它可以处理 2 位数字,因为 2 个元素是一个微弱的测试:
Dim phrases As String() = {"Adele got 2", "Zalgo got 9", "Jack got 8", "Ziggy got 11"}
phrases = phrases.OrderByDescending(Function(q) Int32.Parse(q.Split(" ").Last)).ToArray()
For Each s In phrases
Console.WriteLine(s)
Next
Result:结果:
Ziggy got 11 Zalgo got 9 Adele got 8 Jack got 2
Yes, it's possible.是的,这是可能的。 Add a comparer function, and then sort using it.
添加比较器函数,然后使用它进行排序。 This is the comparer:
这是比较器:
Private Shared Function WhoGotComparer(ByVal x As String, ByVal y As String) As Integer
Dim parseX() As String = Split(x, " got ")
Dim parseY() As String = Split(y, " got ")
If parseX.Length <> 2 Or parseY.Length <> 2 Then Return 0
Return CInt(parseY(1)).CompareTo(CInt(parseX(1))) 'Performs an integer comparison.
End Function
Add it to your code.将其添加到您的代码中。 You can make use of it like this:
您可以像这样使用它:
names.Sort(AddressOf WhoGotComparer)
This should result in the array being sorted in descending order.这应该导致数组按降序排序。 I think that is what you wanted based on the example.
根据示例,我认为这就是您想要的。 If you want to change the order to ascending you can reverse the roles of they x and y parameters in the comparer function, or you can negate the results of the Compare.
如果要将顺序更改为升序,您可以在比较器函数中颠倒它们 x 和 y 参数的作用,或者您可以否定比较的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.