ArrayList and indexOf

  • Thread starter Thread starter tony
  • Start date Start date
T

tony

Hello!

Assume I have created several object of a class called Test and then used
add all these Test object to an ArrayList.

Assume also that in this class Test I have a field with a property called
name.
Assume I add a Test object where the name field is equal to "Nisse"

Now to my question:
Is it possible to find if there exist an object in the ArrayList with the
name="Nisse"

//Tony
 
tony said:
Hello!

Assume I have created several object of a class called Test and then used
add all these Test object to an ArrayList.

Assume also that in this class Test I have a field with a property called
name.
Assume I add a Test object where the name field is equal to "Nisse"

Now to my question:
Is it possible to find if there exist an object in the ArrayList with the
name="Nisse"

Yes - write a loop and check each object.

foreach (Test t in list)
if (t.Name == "Nisse")
// found

If you used List<T> instead of ArrayList (and you're using C# 2.0 on
..NET 2.0), you could do it with a predicate passed to List<T>.FindAll()
/ List<T>.FindIndex(), but it wouldn't really be any less code.

If you were using the LINQ preview of C# 3.0, you could write:

bool found = list.FindIndex(e => e.Name == "Nisse") != -1;

.... but that's not for production use yet. :)

-- Barry
 
Tony,

If the ordering of elements is not important to you you can use Hastable
instead. Hastables registers elements under some key value. You can use
latter on the key to extract the element.

Hashtable ht = new Hashtable()

ht[test.name] = test;

ht["Nisse"] will return the object which proeprty name was Nisse.

Keep in mind that keys cannot duplicate as well as if you change the *name*
property after the object has been added to the hashtable trying to retrieve
the item using the new name won't work. The element needs to be re-added
upon changing the name.
 
Back
Top