Accessing ArrayList index by a key not an index number

  • Thread starter Thread starter Jack Addington
  • Start date Start date
J

Jack Addington

How do I go about accessing elements of an Arraylist using something other
than the index?

I have a class that manages a number of subclasses. Those subclasses are
stored in an arraylist. The subclass has a key property that is a string.
I would like to be able to call Class1.SubClassManager[string key] as
opposed to Class1.SubClassManager[int index].

I tried overriding ArrayList but then I wasn't sure what method to then
override or if there was a simpler method.

thanks

jack
 
Jack,

In this case, you wouldn't use an ArrayList, you would use a Hashtable
(or if you wanted to create a strongly typed Hashtable, use the
DictionaryBase class).

Hope this helps.
 
Everyone is pointing you at a Hashtable, but that is NOT the only solution. If
your collection is small, then you can do your own linear search through the
elements. If your collection is sorted, then you can use BinarySearch with
a custom comparer.

Your options are determined base on your data. If you have plenty of elements
then definitely go to a Hashtable, it will be faster.
 
Or if you insist to use ArrayList's functionality then you can make your
own class that inherits System.Collections.CollectionBase class and
implement functionality for string indexer in it.

Maqsood Ahmed
Kolachi Advanced Technologies
http://www.kolachi.net
 
Back
Top