Click here to Skip to main content
Click here to Skip to main content
Alternative Tip/Trick

Findcontrol using a non recursive approach

, 8 Nov 2011 CPOL
Rate this:
Please Sign up or sign in to vote.
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.)

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)

Share

About the Author

Kabwla.Phone
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 appliction or a patient.
Oddly enough, more people care about the death of their application, than the massacre op people...

Comments and Discussions

 
GeneralThe list approach is extremely* slow especially when you fac... Pinmemberrj458-Nov-11 9:28 
The list approach is extremely* slow especially when you factor the foreach required to use it.
 
Profile it and take a look how terrible foreach is.
Although it is still better than recursive approach.
 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.141223.1 | Last Updated 8 Nov 2011
Article Copyright 2011 by Kabwla.Phone
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid