有什么方法可以使用循环简化我的代码。在Visual Basic中

时间:2015-11-13 13:00:10

标签: vb.net refactoring

我有一个程序,查看为候选人输入的投票,并确定谁得分最低的获胜者。因为用户输入他们的首选项从1到5,其中1是最喜欢的,5是最不喜欢的。如果有最多1次胜利的候选人,如果这仍然是平局,那么其中最多2的候选人。我有一个程序,但想知道我是否可以简化它,然后我继续重复代码来检查谁得到了最多的2等。这是我到目前为止所做的。

    If candidate1 < candidate2 And candidate1 < candidate3 And candidate1 < candidate4 And candidate1 < candidate5 Then
        MsgBox("The winner is" & LblCand1.Text)
    ElseIf candidate2 < candidate1 And candidate2 < candidate3 And candidate2 < candidate4 And candidate2 < candidate5 Then
        MsgBox("The winner is" & lblCand2.Text)
    ElseIf candidate3 < candidate2 And candidate3 < candidate1 And candidate3 < candidate4 And candidate3 < candidate5 Then
        MsgBox("The winner is" & lblCand3.Text)
    ElseIf candidate4 < candidate2 And candidate4 < candidate3 And candidate4 < candidate1 And candidate4 < candidate5 Then
        MsgBox("The winner is" & lblCand4.Text)
    ElseIf candidate5 < candidate2 And candidate5 < candidate3 And candidate5 < candidate4 And candidate5 < candidate1 Then
        MsgBox("The winner is" & lblCand5.Text)
    ElseIf C1V1s > C2V1s And C1V1s > C3V1s And C1V1s > C4V1s And C1V1s > C5V1s Then
        MsgBox("The winner is" & LblCand1.Text)
    ElseIf C2V1s > C1V1s And C2V1s > C3V1s And C2V1s > C4V1s And C2V1s > C5V1s Then
        MsgBox("The winner is" & lblCand2.Text)
    ElseIf C3V1s > C1V1s And C3V1s > C2V1s And C3V1s > C4V1s And C3V1s > C5V1s Then
        MsgBox("The winner is" & lblCand3.Text)
    ElseIf C4V1s > C1V1s And C4V1s > C2V1s And C4V1s > C3V1s And C4V1s > C5V1s Then
        MsgBox("The winner is" & lblCand4.Text)
    ElseIf C5V1s > C1V1s And C5V1s > C2V1s And C5V1s > C3V1s And C5V1s > C4V1s Then
        MsgBox("The winner is" & lblCand5.Text)
    End If

1 个答案:

答案 0 :(得分:4)

我建议您创建一个类Candidate,其中包含每个候选人的分数和名称:

Class Candidate
    Implements IComparable(Of Candidate)

    Public Property Score As Integer
    Public Property Name As String

    Public Function CompareTo(other As Candidate) As Integer Implements IComparable(Of Candidate).CompareTo
        If (other.Score > Me.Score) Then
            Return -1
        ElseIf (other.Score = Me.Score) Then
            Return 0
        Else
            Return 1
        End If
    End Function
End Class

然后,如果您有候选实例的集合,则可以执行以下操作:

Dim myCandidates As New List(Of Candidate)
'fill your list with instances somehow...
MsgBox(String.Format("The winner is {0}", myCandidates.Min().Name))

请注意,Candidate类必须实现the IComparable(Of T) interface,以便实例知道如何将自己与Min()方法进行比较。