Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Search for closest Match

Status
Not open for further replies.

Domino2006

Programmer
Jan 13, 2007
20
0
0
GB
Hi guys girls i have a csv file i have read into 3 listboxes all containing 1 row of the 3 columns from the csv. column 1 & 2 contain numbers. i have for example a number 3002.319 and im trying to figure out how to search the columns in listbox 2 for the closest match i.e. 3002.315. my code is as follows.

Dim strfilename As String = "C:\Documents and Settings\crazy\Desktop\data.CSV"



'File to string vars
Dim objSRFile As StreamReader
Dim strInput, arrStrInput() As String
Dim intCurrPos As Integer
Dim sitename, sitepos1, sitepos2 As String


objSRFile = File.OpenText(strfilename)
While objSRFile.Peek <> -1


strInput = objSRFile.ReadLine
arrStrInput = Split(strInput, ",", , CompareMethod.Text)
For intCurrPos = 0 To arrStrInput.Length - 1
Select Case intCurrPos
Case 0
sitename = arrStrInput(intCurrPos)
Case 1
sitepos1 = arrStrInput(intCurrPos)
Case 2
sitepos2 = arrStrInput(intCurrPos)



ListBox1.Items.Add(sitename)
ListBox2.Items.Add(sitepos1)
ListBox3.Items.Add(sitepos2)
End Select
Next

End While

End Sub
 
I would say that using a DataTable to store the data in and binding the ListBoxes to it would be a better performance option.

If you use a DataTable you can use its functions for searching for rows, which is much faster than going through each item in a ListBox (For ... Next).

You can then use the DataTable.Select function to find the row(s) for you.
First search for an exact match:
Rows = DT.Select("sitepos1 = '" & SomeNum & "'")(0)

Then if none found, search for above:
AboveRows = DT.Select("sitepos1 > '" & SomeNum & "'", "sitepos1")
Or below:
BelowRows = DT.Select("sitepos1 < '" & SomeNum & "'", "sitepos1 DESC")

You could check for the closest row by:
If (AboveRows(0).Item("sitepos1") - SomeNum) > (SomeNum - BelowRows(0).Item("sitepos1")) Then
ClosestRow = BelowRows(0)
Else
ClosestRow = AboveRows(0)
End If


 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top