Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / IEnumerable

Findcontrol using a non recursive approach

0.00/5 (No votes)
8 Nov 2011CPOL 8.2K  
Implemented with a queue and some newfangled yields.Since a queue does not have an 'EnqueueRange', we will still have to do a loop. Of course, enqueue range would be a nice extension method.Excusing the overhead created by the yield, this might use less memory if there are many controls. (Or...

Implemented with a queue and some newfangled yields.


Since a queue does not have an 'EnqueueRange', we will still have to do a loop. Of course, enqueue range would be a nice extension method.


Excusing the overhead created by the yield, this might use less memory if there are many controls. (Or when adapting the code for any composite/nested structure.)


C#
public static IEnumerable<control> FindControls(Control controlTop)
{
    var queue = new Queue<control>();

    queue.Enqueue(controlTop);

    while (queue.Count > 0)
    {
        var current = queue.Dequeue();
        var children = current.Controls;
        int count = children.Count;

        for (int index = 0; index < count; index++)
        {
            queue.Enqueue(children[index]);
        }
        
        yield return current;
    }
}

Hmm, does not feel 'as tight' as using the list... Still the internet and the pro's have a lot to say about 'clever code'.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)