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

时间:2015-07-28 15:13:19

标签: arrays vb.net position

我的 ComboBox.Text 中有一个随机值,我需要在所有 ComboBox.Items 中找到最接近的值,最后在中设置此值> 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

1 个答案:

答案 0 :(得分:1)

Assuming that you want to return the index of the closest value from the ComboBox, you need to keet track of which value is currently the closest as you loop through all the ComboBox items.

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