Click here to Skip to main content
15,881,089 members
Articles / Ienumerable
Alternative
Tip/Trick

Findcontrol using a non recursive approach

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
8 Nov 2011CPOL 7.8K   1
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)


Written By
Software Developer (Senior)
Netherlands Netherlands
Doing that 'computer thing' ever since the C64.

Sometimes I feel that being a programmer is much like being a doctor: You just have to know everything and if you don't, something dies.

Either being an application or a patient.

Oddly enough, more people care about the death of their application, than the massacre of people...

Comments and Discussions

 
GeneralThe list approach is extremely* slow especially when you fac... Pin
rj458-Nov-11 8:28
rj458-Nov-11 8:28 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.