Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 将文件加载到数组中,然后从最高到最低排序_Arrays_Vb.net_File - Fatal编程技术网

Arrays 将文件加载到数组中,然后从最高到最低排序

Arrays 将文件加载到数组中,然后从最高到最低排序,arrays,vb.net,file,Arrays,Vb.net,File,我试图在加载到数组中的文件中排序最大分数。目前,程序打开文件,然后读取,然后将每一行分成两部分——一个名称和一个分数;然后将其存储在一个数组中。我不知道如何对数组进行排序以找到最大的10个分数并将其放入列表框中。此时,程序会找到任何高于0的分数并将其放入列表框中 Dim FileNum As Integer = FreeFile() FileOpen(FileNum, "GameResultsFile", OpenMode.Input) For index = 0 T

我试图在加载到数组中的文件中排序最大分数。目前,程序打开文件,然后读取,然后将每一行分成两部分——一个名称和一个分数;然后将其存储在一个数组中。我不知道如何对数组进行排序以找到最大的10个分数并将其放入列表框中。此时,程序会找到任何高于0的分数并将其放入列表框中

    Dim FileNum As Integer = FreeFile()

    FileOpen(FileNum, "GameResultsFile", OpenMode.Input)

    For index = 0 To 99
        Dim temp() As String = LineInput(FileNum).Split(",") 'CUTTING LINE INTO TWO SECTIONS


        MemoryGame.HighScores(index).Name = temp(0) 'NAME (First Part of Line)
        MemoryGame.HighScores(index).Score = temp(1) 'SCORE (Second Part of Line)

        If temp(1) > 0 Then 'If any of the scores is above 0 then
            ListBox1.Items.Add(temp(0) + " " + temp(1)) ' display the name of the person who got that score and their score
        End If




    Next
    FileClose()

我会用电脑做类似的事情

首先,我会像这样从你的文本文件中加载数据,并将数据保存到a,类型将是下面的
Player

    '' Get Data From Text File And Create An Anonymous Type
    Private Sub LoadPlayerAndScore(path As String)

    '' Load data from text file
    Dim data = From line In System.IO.File.ReadAllLines(path)
               Let val = line.Split(",")
               Select New With {Key .Name = val(0), Key .Score = val(1)}

    '' Save data to list
    For Each pair In data
        Dim player As New Player With {
            .Name = pair.Name,
            .Score = pair.Score
        }
        playersList.Add(player)
    Next

End Sub
然后我将继续创建一个player类,该类将实现上面列出的IComparable

Class Player
Implements IComparable(Of Player)
Public Property Name As String
Public Property Score As Integer

Public Sub Player(ByVal name As String, ByVal score As Integer)
    Me.Name = name
    Me.Score = score
End Sub

'' Sort Player From The Hightest Score To The Lowest Score
Private Function IComparable_CompareTo(other As Player) As Integer Implements IComparable(Of Player).CompareTo
    Return other.Score.CompareTo(Me.Score)
End Function
End Class
然后我将创建一些公共变量,如

Dim playersList As New List(Of Player)
Dim fileLocation As String = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Settings.txt")
更改文件位置的路径。

最后,在
中,我会这样称呼它

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
    '' Load Data From Text File On Desktop
    LoadPlayerAndScore(path:=fileLocation)

    '' Sort List
    playersList.Sort()

    '' Add Values To List
    For Each p As Player In playersList
        ListBox1.Items.Add("Name: " + p.Name + " Score: " + p.Score.ToString())
    Next

End Sub
下面是代码的整体外观

Public Class Form1
Dim playersList As New List(Of Player)
Dim fileLocation As String = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Settings.txt")

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
    '' Load Data From Text File On Desktop
    LoadPlayerAndScore(path:=fileLocation)

    '' Sort List
    playersList.Sort()

    '' Add Values To List
    For Each p As Player In playersList
        ListBox1.Items.Add("Name: " + p.Name + " Score: " + p.Score.ToString())
    Next

End Sub
'' Get Data From Text File And Create An Anonymous Type
Private Sub LoadPlayerAndScore(path As String)

    '' Load data from text file
    Dim data = From line In System.IO.File.ReadAllLines(path)
               Let val = line.Split(",")
               Select New With {Key .Name = val(0), Key .Score = val(1)}

    '' Save data to list
    For Each pair In data
        Dim player As New Player With {
            .Name = pair.Name,
            .Score = pair.Score
        }
        playersList.Add(player)
    Next

End Sub
End Class

Class Player
Implements IComparable(Of Player)
Public Property Name As String
Public Property Score As Integer

Public Sub Player(ByVal name As String, ByVal score As Integer)
    Me.Name = name
    Me.Score = score
End Sub
'' Sort Player From The Hightest Score To The Lowest Score
Private Function IComparable_CompareTo(other As Player) As Integer Implements IComparable(Of Player).CompareTo
    Return other.Score.CompareTo(Me.Score)
End Function
End Class
这是我得到的输出,这是文本文件数据的样子。
安德鲁,25岁
MERVE,12

RUZGAR,50

对于排名前十的人,请按照上面的评论进行操作。

试试这个怎么样

Dim sortedArray = _
    File _
        .ReadAllLines("GameResultsFile") _
        .Select(Function (line) line.Split(","c)) _
        .Select(Function (parts) New With { .Name = parts(0), .Score = Integer.Parse(parts(1)) }) _
        .OrderByDescending(Function (x) x.Score) _
        .Select(Function (x) x.Name & " " & x.Score)
        .ToArray()

For Each item As String In sortedArray
    ListBox1.Items.Add(item)
Next

评论和解释一致

'Note Imports System.IO
    Structure Player
        Public Score As Integer
        Public Name As String
        'Added a constructor to the structure to make it easy to add new Player
        Public Sub New(myScore As Integer, myName As String)
            Score = myScore
            Name = myName
        End Sub
    End Structure

    Private HighScores(99) As Player

    Private index As Integer 'used in both LoadArray and SortAndDisplayArray

    Private Sub LoadArray()
        Using sr As New StreamReader("GameResultsFile.txt")
            Dim line As String
            Do While sr.Peek() > -1 'Peek checks if there is another character in the file
                line = sr.ReadLine()
                Dim temp() As String = line.Split(","c) 'CUTTING LINE INTO TWO SECTIONS
                'Notice the elements of the temp array are switched to match the
                'Player constructor (Sub New)
                HighScores(index) = New Player(CInt(temp(1)), temp(0))
                index += 1 'not only keeps track of the index but remembers how many elements
                'we have added to HighScores
            Loop
        End Using
    End Sub

    Private Sub SortAndDisplayArray()
        'This is the LINQ way to do it, you can do a great deal in one line of code
        'There is a loop underneath but you don't have to write it.
        'I added a Take clause so we will not get a bunch of 0- in the list box going up to index 99
        ' You might want to show, for example only the top ten scorers, so change to Take 10
        Dim orderArray = From scorer In HighScores Order By scorer.Score Descending Select $"{scorer.Score} - {scorer.Name}" Take index
        ListBox1.DataSource = orderArray.ToList
    End Sub

我仍然认为列表(T)会更容易,但我感觉您的任务要求您使用数组。

首先,摆脱旧的VB6样式的I/O。您应该使用
System.IO
命名空间中的类型。从阅读文本文件的
StreamReader
类开始。您应该定义一个类型来表示一个玩家的分数,名称为
String
属性,分数为
Integer
属性。当您逐行读取文件时,创建该类型的实例并将其添加到集合中,即
List(of T)
,其中
T
是您的类型。然后,您可以调用该集合上的
Sort
按分数排序,然后
Take
获取前10项。调用
到阵列
,然后绑定到
列表框
。非常感谢!唯一的问题是如何先显示名称然后显示分数的排行榜?在Linq的Select部分,将“{scorer.score}-{scorer.name}”更改为“{scorer.name}-{scorer.score}”告诉编译器替换变量是花括号。空格和连字符是文字。您可以将连字符更改为逗号或任何您想要的字符,也可以只留下空格。最后一件事是,您在“我添加了一个Take子句,这样我们就不会在列表框中得到一堆0-在索引99”中,这不起作用,因为列表框中仍然充满了0。您确实在表单级别将
私有索引作为整数
,而不是在子目录中,正确的?Take索引在Linq的最末端,是吗?它适用于我的五月样本文件。你能在记事本中打开你的文件,并检查你最后一个条目以外的内容吗。我的意思是,可能是一个返回或标签,你看不到。pastebin.com/Rr43EwwR-我相信这一切都是正确的,但它仍然在加载零