Cancel
Showing results for 
Search instead for 
Did you mean: 

Use of .BinarySearch - How to check for "true" nearest?

Phenom
Phenom

To all,

 

As part of small programme I need to find the nearest value in the X data of a (AFU) record to the value specifed by the user. I am using .BinarySearch for that but I'd like some advise/pointer.

 

1. Is this the best way of searching for the nearest value?

2. (assuming tha the exact value is not in the list)  is there a way or returnign the "true" nearest value? I lifted the example from microsoft website, see below for part of my test code, and it will always return the rank above. if you search for say 252 in the following list (200,250,300) then you'll get 300 whereas the nearest is 250. Is the only to compare values at (index-1) & (index) ?

3. Maybe I am better of using a Dictionary()

 

Thanks

Regards

 

	index = ListToSearch.BinarySearch(dbValueToFind)
	theLW.WriteLine("index is " & index.ToString) 

	If index < 0 Then
		index = index Xor -1
		theLW.WriteLine(" value at the index is " & ListToSearch.Item(index).ToString)
	Else
		theLW.WriteLine("value at the index is " & ListToSearch.Item(index).ToString)
	End if
Production: NX9.0.3.4, NX10.0.2.6
Development: VB.NET (amateur level !)
3 REPLIES

Re: Use of .BinarySearch - How to check for "true" nearest?

Honored Contributor
Honored Contributor

Re: Use of .BinarySearch - How to check for "true" nearest?

Phenom
Phenom

Thanks. I cannot use LINQ

I thought that there would be something easy to use! Looks like I may need a simple check (calculate the difference between the value to find and the value at index, index-1

Production: NX9.0.3.4, NX10.0.2.6
Development: VB.NET (amateur level !)
Highlighted

Re: Use of .BinarySearch - How to check for "true" nearest?

Honored Contributor
Honored Contributor

Some of the samples do not use LINQ; looks to be a lot easier if they would let us use it, though.