Collections of Collections in C#

  • Thread starter Thread starter jonathan
  • Start date Start date
J

jonathan

Hi

I have a class that contains an array of another class:

public abstract class Node {}

public class elem1 : Node {
public ArrayList NodeItems1=new ArrayList ();
}

public class elem2 : Node {
public ArrayList NodeItems2=new ArrayList ();

}

So i could have such a tree:
Node
+elem1
++elem2
+elem1
++elem1
+elem2
+elem2
++elem1

How could i iterate over this collections of collections ?

Thanks
Jo
 
Hi,

Why you create two classes with the same structure?

You should be fine with elem1 only, now if you wanna to create a tree
structure you should have to implement it from the Node class, as a node can
be a node or a leaf.
You should also think of using a Strong typed collection instead of
ArrayList, safer and easier to use

maybe something like this:
class Node
{
public ArrayList Childrens=new ArrayList (); //

//Know if I have children
public bool HasChildren{ get{ return Childrens.Count>0;}
}

with the above structure you can create the structure you want.
How to iterate on it depends of how you wanna do it. if you need to return
the nodes ( using an iterator ) or just do some internal process

void ProcessNodes( Node startnode )
{
DoSomething( startnode )

if ( startnode.HasChildren()
foreach( Node currentnode in startnode.Childrens )
ProcessNode( currentnode )

}

The above method do a Deep search first , just as an example.

Cheers,
 

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

Back
Top