我无法将文本文件获取到数组,然后对数组进行排序

时间:2014-12-20 00:17:33

标签: arrays vb.net sorting numbers text-files

我需要将保存的文本文件读入数组,然后以数字方式对其进行排序。这很难,因为文本文件是:

10 First name:bob
30 first name:sam

等等。它没有按照这种方式排序,它保存在文本文件中的得分结构"名字" &安培;名字。我必须按数字排序从最高到最低。我试过sort.array。但这仅用于按字母顺序排序只有单词的数组。我尝试过其他流程,但似乎无法工作。有人能帮我吗。谢谢

1 个答案:

答案 0 :(得分:0)

使用LINQ:

    Dim DataFileName As String = "C:\Users\Mike\Documents\Data.txt"
    Dim SortedByScore = From line In System.IO.File.ReadLines(DataFileName)
                        Let score = CInt(line.Split(" ")(0))
                        Order By score Descending
                        Select line
    For Each line As String In SortedByScore
        Debug.Print(line.ToString)
    Next

将Array.Sort()与Comparer一起使用:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim DataFileName As String = "C:\Users\Mike\Documents\Data.txt"
    Dim Lines() As String = System.IO.File.ReadAllLines(DataFileName)
    Array.Sort(Lines, AddressOf SortByScore)
    For Each line As String In Lines
        Debug.Print(line.ToString)
    Next
End Sub

对于问题中指定的原始格式:10 First name:bob

Private Function SortByScore(ByVal x As Object, ByVal y As Object) As Integer
    Dim valuesX() As String = x.ToString.Split(" ")
    Dim valuesY() As String = y.ToString.Split(" ")
    Return CInt(valuesY(0)).CompareTo(CInt(valuesX(0)))
End Function

如果格式实际为:bob{vbTab}score :10,请尝试:

Private Function SortByScore(ByVal x As Object, ByVal y As Object) As Integer
    Dim valuesX() As String = x.ToString.Split(":")
    Dim valuesY() As String = y.ToString.Split(":")
    Return CInt(valuesY(1)).CompareTo(CInt(valuesX(1)))
End Function