循环vb.net中的排名

时间:2016-08-04 08:51:50

标签: vb.net loops while-loop numbers

我目前从数据库中提取数据,并在我遍历它们时对它们进行排名。此类数字的示例为45, 45, 67, 99, 34, 65, 88, 22, 90, 90, 90, 23, 55, 46。这些是总共14个数字,我想循环并分配排名。

 Dim i As Integer() = {45, 45, 67, 99, 34, 65, 88, 22, 90, 90, 90, 23, 55, 46}
    Dim lastScore As Integer
    Dim position As Integer = 0

    For Each i1 In i
        If Val(lastScore) <> Val(i1) Then
            position += 1
            Console.WriteLine(position & vbCrLf)
        ElseIf Val(lastScore) = Val(i1) Then
            Console.WriteLine(position & vbCrLf)
            position += 1
        End If
        lastScore = Val(i1)
    Next

上面代码的当前输出是:

1, 1, 3, 4, 5, 6, 7, 8, 9, 9, 10, 12, 13, 14

哪个错了。预期的输出应该是:

1, 1, 3, 4, 5, 6, 7, 8, 9, 9, 9, 12, 13, 14

我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:2)

这是一个创建预期输出的丑陋代码:

    Dim i As Integer() = {45, 45, 67, 99, 34, 65, 88, 22, 90, 90, 90, 23, 55, 46}
    Dim lastScore As Integer
    Dim lastScorePosition As Integer
    Dim position As Integer = 1

    For Each i1 In i
        If Val(lastScore) <> Val(i1) Then
            Console.Write(position & ",")
            lastScorePosition = position
            lastScore = Val(i1)
        Else
            Console.Write(lastScorePosition & ",")
        End If
        position += 1
    Next

答案 1 :(得分:0)

预期结果不正确。即为什么没有排名2?

使用相对简单的代码实现简单排名:

-relaxed

输出结果为:

Sub Main()

    Dim i As Integer() = {45, 45, 67, 99, 34, 65, 88, 22, 90, 90, 90, 23, 55, 46}
    Dim lastScore As Integer
    Dim position As Integer

    Dim sb As New StringBuilder

    For Each i1 In i
        If Not lastScore = i1 Then position += 1
        sb.Append(position & ", ")
        lastScore = i1
    Next

    sb.Remove(sb.Length - 2, 2)
    Console.WriteLine(sb.ToString)

    Console.ReadLine()
End Sub