ArrayList OF Objects

  • Thread starter Thread starter thomson
  • Start date Start date
T

thomson

Hi All,
i do have an array list of objects

eg: ArrayList al=new ArrayList();
al.Add(new MyOb(1);
al.Add(new MyOb(2);


from this i need to access a particular object values , how do i do
it??

eg:
From the Arraylist how do get object with variable 2


Thanks in Advance

thomson
 
thomson said:
Hi All,
i do have an array list of objects

eg: ArrayList al=new ArrayList();
al.Add(new MyOb(1);
al.Add(new MyOb(2);


from this i need to access a particular object values , how do i do
it??

eg:
From the Arraylist how do get object with variable 2

Use a List<MyOb> instead of an ArrayList.
 
You added second value at index 1 (0-based array). So you can get it back as

object o = al[1];

If you need to check type, use GetType method

if (al[1].GetType() == typeof(MyObj)) { ... }

See documentation for ArrayList - there are severall access methods
available
 
Hi thomson,

Base method is foreach(object in al) { if (object.Property == 2) ... } if
you are on .NET 1.1
or use List<object> list and list.Find() on .NET 2.0.

It's for values. For just one value as key it's better to consider using
Hashtable(1.x)/Dictionary<>(2.0)

Regards, Alex
[TechBlog] http://devkids.blogspot.com
 
You added second value at index 1 (0-based array). So you can get it back as

object o = al[1];

If you need to check type, use GetType method

if (al[1].GetType() == typeof(MyObj)) { ... }

Or if you just want to know if you can treat the object as a certain type

if(al[1] is MyObj) { ... }
 
Hi All,
i do have an array list of objects

eg: ArrayList al=new ArrayList();
al.Add(new MyOb(1);
al.Add(new MyOb(2);


from this i need to access a particular object values , how do i do
it??

eg:
From the Arraylist how do get object with variable 2


Thanks in Advance

thomson

MyOb obj = (MyOb)al[1];

Use [] to access a particular item in a list given its index. al[1] will return your item, but as an Object reference so you need to cast it toMyOb.

Anyhow, if you are going to use a single type of items in a list, use List instead (.Net 2.0) as you can then access the items without having toworry about types. You'll get a compiler or runtime error if you put anything else but the correct type in such a list.

List<MyOb> al = new List<MyOb>();
al.Add(new MyOb());
al.Add(new MyOb());

MyOb obj = al[1];
 
Back
Top