Home > front end >  How to Get the Mid Value From List in VB .NET
How to Get the Mid Value From List in VB .NET

Time:03-02

I have simple loop where I am storing values to my list. I want to get the mid value of that list.

Here is how I am doing it:

Dim listOfValues As New List(Of Double)
For i = 1 To 5
    Values.Add(i)
Next

Values.Sort()

' How can I get the Mid Value of That List and store it into some other variable

Dim midValue = Values.mid() ' Something like this

How can I get the Mid Value from That List?
I want it to work with both odd and even values of the loop.

CodePudding user response:

in case of even number what we have to do is we have to find the average of the two numbers and then we have to add the floor function

You can use math to calculate the mid-index and mid-value:

Dim midValue As Double = 0
Dim midIndex As Int32 = listOfValues.Count \ 2 ' integer division operator
If listOfValues.Count > 0
    If listOfValues.Count Mod 2 = 0
        ' even number, calculate the midValue from average of 2 in middle
        midValue = (listOfValues(midIndex)   listOfValues(midIndex-1)) \ 2
    Else
        midValue = listOfValues(midIndex)
    End If
End If

As commented i'm using the integer division operator \ to get the integer value of a double(the remainder is truncated) which is simular to Math.Floor.

  • Related