如何从 VB .NET 中的列表中获取中间值

How to Get the Mid Value From List in VB .NET

我有一个简单的循环,我将值存储到我的列表中。我想获得该列表的中间值。

这是我的做法:

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

如何从该列表中获取中间值?
我希望它能同时处理循环的奇数和偶数。

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

您可以使用数学计算 mid-index 和 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

正如所评论的,我正在使用整数除法运算符 \ 来获取与 Math.Floor.

相似的双精度整数值(余数被截断)