在vb中排序结构数组

时间:2015-03-04 14:04:23

标签: arrays vb.net sorting

我做了一个简单的问答游戏,用户被问到10个问题,得到10分的结果。我正在编排排行榜,我想将分数从最高到最低排序。我使用了一个结构来将数据一起存储,并使用一维数组来存储数据。

  Structure userData
        Dim userName As String
        Dim score1Text As Integer
        Dim score2Text As Integer
        Dim score3Text As Integer
        Dim average As Integer
    End Structure

    Dim users(99) As userData

如何按分数对数组进行排序并将结构保持在一起?

1 个答案:

答案 0 :(得分:0)

我会在你的UserData类上实现IComparable(使它成为一个类,而不是一个结构)

Public Class UserData : Implements IComparable(Of UserData)
    Public Property userName As String
    Public Property score1 As Integer
    Public Property score2 As Integer
    Public Property score3 As Integer
    Public Property average As Integer ' I'd make this Double or something, but this is what you had.

    Public Function CompareTo(other As UserData) As Integer Implements IComparable(Of UserData).CompareTo
        If other Is Nothing Then Return 1
        Return average.CompareTo(other.average)
    End Function
End Class

然后在其他地方......

    Dim users As New List(Of UserData)
    ' Fill in users somehow...

    users.Sort()