[Mono-dev] Action<T> used

Alejandro Serrano trupill at yahoo.es
Tue Jul 11 04:41:21 EDT 2006


public void ForEach (Node node, Action<Node> action)
{
    action (node)
    foreach (Node child in this.Subnodes) ForEach (child, action);
}

Hope this helps ;-)

Other solution would be using IEnumerable

public class Node : IEnumerable<Node>
{
    ...

    public IEnumerator<Node> EnumerateDescendants ()
    {
       Queue<Node> todo = new Queue<Node> ();
       todo.Enqueue (this);
       while (todo.Count > 0)
       {
          Node node = todo.Enqueue ();
          yield node;
          foreach (Node child in node.Subnodes) todo.Enqueue (child);
       }
    }
}

Now you can use:

foreach (Node node in firstNode.EnumerateDescendants ())
    doWhatYouWant (node);

Alejandro Serrano


Piotr Zurek escribió:
> Hi guys,
>
> I have created a simple tree structure using List<T>.
> Below is the metod that I use to count all the nodes in that structure.
>
>         public void CountDescendants()
>         {
>             _totalcount = 0;
>             Queue<Node> todo = new Queue<Node>();
>             todo.Enqueue(this);
>             while (todo.Count > 0)
>             {
>                 Node node = todo.Dequeue();
>                 foreach (Node child in Node.Subnodes) todo.Enqueue(child);
>                 _totalcount++;
>             }
>         }
>
> I have been podering on how to create a simple ForEach method for my
> Node class that would allow me executing different commands on all
> elements of the tree.
> Probably the Action<T> delegate is the way to go here but I ain't got
> a clue how to use it. Any ideas?
>
> Cheers
> Piotr
> _______________________________________________
> Mono-devel-list mailing list
> Mono-devel-list at lists.ximian.com
> http://lists.ximian.com/mailman/listinfo/mono-devel-list
>
>   


	
	
		
______________________________________________ 
LLama Gratis a cualquier PC del Mundo. 
Llamadas a fijos y móviles desde 1 céntimo por minuto. 
http://es.voice.yahoo.com



More information about the Mono-devel-list mailing list