如何在 VB.Net 中找到数组最小值的 id

How do I find the id of the minimum value of an array in VB.Net

我的 ComboBox.Text 中有一个随机值,我需要在所有 ComboBox.Items[= 中找到最接近的值20=] 最后在 ComboBox.Text

中设置这个值

我的代码已经找到最接近的值,但我不知道这个数字的 ID 是什么,无法将它关联到我的 ComboBox.Items:

Function FindItemcbxWR()
        Dim i, x(3) As Integer
        For i = 0 To 3
            x(i) = Math.Abs(CInt(Me.cbxWR.Text) - CInt(Me.cbxWR.Items(i)))
        Next
        x.Min() 'I already know
        Return 'I don't know how to proceed to get my id of my x.Min() to return
End Function
Private Sub MainForm_Load(sender As Object, e As EventArgs)
        Dim closeValueID As Integer
        closeValueID = FindItemcbxWR()
        Me.cbxWR.Text = Me.cbxWR.Items(closeValueID)
End Sub

假设您想要return ComboBox 中最接近的值的索引,您需要在遍历所有ComboBox 项目时跟踪当前最接近的值。

Function FindItemcbxWR() As Integer
    Dim ind As Integer, diff As Integer = Integer.MaxValue 
    For i As Integer = 0 To cbxWR.Items.Count - 1
        Dim diffTest As Integer = Math.Abs(CInt(cbxWR.Text) - CInt(cbxWR.Items(i)))
        If diffTest < diff Then
            ind = i 
            diff = diffTest 
        End If
    Next
    Return ind
End Function