订购号码从最高到最低

时间:2015-10-24 13:46:51

标签: vb.net sorting

对于我游戏中的高分页面,我从文本文件中取出第1到第5个最高值,然后在文本框中显示它们但我遇到的问题是我的代码将每个数字看作一个单独的数字,例如,43将被读为4和3.这意味着我的高分页面从不显示高于9的分数。如果程序在每行上包含一个新数字,则文本文件位于资源中。

我该如何解决这个问题?

以下代码。

'Part 1: Determine Resource File Path based on Debugging mode or Published mode  
Dim ResourceFilePathPrefix As String
If System.Diagnostics.Debugger.IsAttached() Then
    'In Debugging mode  
    ResourceFilePathPrefix = System.IO.Path.GetFullPath(Application.StartupPath & "\..\..\resources\")
Else
    'In Published mode  
    ResourceFilePathPrefix = Application.StartupPath & "\resources\"
End If

'Part 2: Write the text file
Dim lines() As String = File.ReadAllLines(ResourceFilePathPrefix & "scores.txt")
Array.Sort(lines)
Array.Reverse(lines)
P1Score.Text = lines(0)
P2Score.Text = lines(1)
P3Score.Text = lines(2)
P4Score.Text = lines(3)
P5Score.Text = lines(4)

1 个答案:

答案 0 :(得分:0)

您需要先将分数转换为整数,然后才能对数字进行排序,否则它们将按文本排序(分数存储在文件中的方式)。

'Part 2: Write the text file
Dim lines() As String = File.ReadAllLines(ResourceFilePathPrefix & "scores.txt")

Dim scores As New System.Collections.Generic.List(Of Integer)
For Each line As String in lines
    scores.Add(Convert.ToInt32(line))
Next

scores.Sort()
scores.Reverse()

P1Score.Text = scores(0)
P2Score.Text = scores(1)
P3Score.Text = scores(2)
P4Score.Text = scores(3)
P5Score.Text = scores(4)

或使用Linq:

'Part 2: Write the text file
Dim lines() As String = File.ReadAllLines(ResourceFilePathPrefix & "scores.txt")
Dim scores = lines.Select(Function(x) Convert.ToInt32(x)).OrderByDescending(Function(x) x)
P1Score.Text = scores(0)
P2Score.Text = scores(1)
P3Score.Text = scores(2)
P4Score.Text = scores(3)
P5Score.Text = scores(4)