BlackPearl - 1 year ago 88
Vb.net Question

# Rank numbers in a loop vb.net

I currently pull data from database and rank them when i loop through them. Example of such numbers are

`45, 45, 67, 99, 34, 65, 88, 22, 90, 90, 90, 23, 55, 46`
. These are a total of 14 numbers, I want to loop through and assign rank.

`````` 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
``````

The current output of the code above is;

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

Which is wrong. The expected output is suppose to be;

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

How can I achieve this?

Here is an ugly code which creates the expected output:

``````    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
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download