Searching in SortedList

G

Georg

Hi,
I would like to use a SortedList collection to store numeric data items with
a key (numeric location). When I have a key which is not stored in the
SortedList and which should not be stored but I just want to know at which
index location it would be stored according the sort order. If I would be
able to get the noughbours of this key in the List I could do an
interpolation with the neighbour items to calculate the values for the this
key.
Of course I could Add the new key and find at which index it is stored and
delete it afterwards, but this is not very nice and efficiency.

Can anybody help?

Georg
 
N

Nicholas Paldino [.NET/C# MVP]

Georg,

Instead of using a SortedList, I would use an array, or an ArrayList
which you keep sorted (when you insert new items). Then, you can do a
binary search on the array/arraylist to find the appropriate place in the
array/arraylist where an item would be inserted.

You can then map the elements of the array to whatever other data you
have in a hashtable or dictionary.

Hope this helps.
 
H

Helge Jensen

Georg said:
Of course I could Add the new key and find at which index it is stored and
delete it afterwards, but this is not very nice and efficiency.

If you aren't iterating the list this may well be the easiest solution.
whether it is efficient *enough*, I would let user-experience decide, or
maybe a profiler.

The usual solution is for IndexOf to return ~i if the object looked for
should have been at position i, but wasn't, but unfortunatly SortedList
doesn't do that. System.Array.BinarySearch does this -- so much for
consistency in the collections in C#1 :)
Can anybody help?

You can do the binary search yourself. If you search for some
example-code, this operation is called lower_bound in c++
standard-library terms.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top