ArrayList OF Objects

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
 
F

Fabio

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.
 
A

AlexS

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
 
A

Alex Meleta

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
 
M

Morten Wennevik [C# MVP]

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) { ... }
 
M

Morten Wennevik [C# MVP]

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];
 

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

Similar Threads


Top