Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.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
Vb.net 在VB中按整数降序排列整数和字符串列表_Vb.net_Sorting - Fatal编程技术网

Vb.net 在VB中按整数降序排列整数和字符串列表

Vb.net 在VB中按整数降序排列整数和字符串列表,vb.net,sorting,Vb.net,Sorting,我必须制作这个程序,对游戏的高分进行排序,然后使用用户名列表从大到小显示它们。到目前为止,我写了: Public highscore As New List(Of HighScores) highscore.Add(New HighScores("Jeremias", 6)) highscore.Add(New HighScores("Tom", 1)) highscore.Add(New HighScores("sdf", 5)) highscore.Add(New HighScores("

我必须制作这个程序,对游戏的高分进行排序,然后使用用户名列表从大到小显示它们。到目前为止,我写了:

Public highscore As New List(Of HighScores)

highscore.Add(New HighScores("Jeremias", 6))
highscore.Add(New HighScores("Tom", 1))
highscore.Add(New HighScores("sdf", 5))
highscore.Add(New HighScores("asfd", 1))

highscore.Sort()
highscore.Reverse()

Console.WriteLine("------High Scores-----")
For Each scores In highscore
     Console.WriteLine(scores)
Next
Console.WriteLine("----------------------")
高分班:

Public Class HighScores
    Public name As String
    Public score As Integer

    Public Sub New(ByVal name As String, ByVal score As Integer)
        Me.name = name
        Me.score = score
    End Sub

    Public Overrides Function ToString() As String
        Return String.Format("{0}, {1}", Me.name, Me.score)
    End Function
End Class

通常我只使用.Sort()和.Reverse()对列表进行排序,但在这种情况下,我认为我无法做到这一点。你知道我如何重写这个/只是简单地对列表排序吗?

你可以指定如何以各种方式对
列表(共T个)
进行排序。最简单的方法是:

highscore.Sort(Function(x, y) y.score.CompareTo(x.score))
它使用重载
Sort
,接受一个
比较(T)
委托,并为该委托使用Lambda表达式。请注意,Lambda参数是
x
y
,主体在
y
分数上调用
CompareTo
。这一点很关键,因为这使排序按降序进行,并且不需要调用
Reverse

请注意,可以使用命名方法而不是Lambda。这种方法如下所示:

Private Function CompareHighScoresByScoreDescending(x As HighScores, y As HighScores) As Integer
    Return y.score.CompareTo(x.score)
End Function
highscore.Sort(AddressOf CompareHighScoresByScoreDescending)
然后,要排序的代码如下所示:

Private Function CompareHighScoresByScoreDescending(x As HighScores, y As HighScores) As Integer
    Return y.score.CompareTo(x.score)
End Function
highscore.Sort(AddressOf CompareHighScoresByScoreDescending)
在比较对象进行排序时,约定使用-1、0和1表示相对位置。这就是
CompareTo
所做的,因此这就是我们的比较方法在这里所做的。如果您调用的
CompareTo
对象在概念上小于您传入的对象,则结果为-1。1表示第一个对象大于第二个对象,0表示它们相等。该方法可以重写如下:

Private Function CompareHighScoresByScoreDescending(x As HighScores, y As HighScores) As Integer
    If y.score < x.score Then
        Return -1
    ElseIf y.score > x.score Then
        Return 1
    Else
        Return 0
    End If
End Function

谢谢你,这正是我想要的!