views:

392

answers:

3

I have an arraylist of objects, I would like to know the index within the arraylist of the object that contains a certain value, is there a built-in way to do the search?

I know I could simply iterate through the arraylist to find the correct value e.g. :

ReportToFind="6"

For i = 0 To ReportObjList.Count - 1
    If ReportObjList.Item(i).ReportCode = ReportToFind Then
        ReportName.Text = ReportObjList.Item(i).ReportName ' found it - show name
        Exit For
    End If
Next

Is the only other solution be to replace this code a binary search?

.Net 1.1

+1  A: 

You need to use better data structures in the case that searching through a list is a problem. You can use a binary search for your arraylist in the case that your list is sorted with respect to the value to be searched. In other cases you would be better of using smarter data structures such as a binary tree or a map.

Markus Koivisto
"better data structures" - better examples required here, perhaps ? Still, +1 for direction.
AmitK
It's not really possible to give a flat out answer unless the exact problem statement is clear. Different data structures have different strengths and disadvantages and as such it's up to the developer/designer to be well versed in the basic data structures to be able to determine which tool best suits the job.
Markus Koivisto
A: 

I don't know if .Net 1.1 has it, but you could try the .IndexOf method on your array list.

ajh1138
A: 

It looks like you need to index your reportObjectList by reportCode in addition to the item index. You can do this either in a second parallel list with the reportCode as the index and the itemIndex as the value.

Beth