Using Linq to Find a Control

I think Every one has one time or the other tried to find a control by looping over and find the required control, but we can use Linq to do the same thing.

 public static class PageExtensions
    {
        public static IEnumerable<control> All(this ControlCollection controls)
        {
            foreach (Control control in controls)
            {
                foreach (Control grandChild in control.Controls.All())
                    yield return grandChild;
 
                yield return control;
            }
        }
    }
</control>

Then you can use as a Linq Expression

var ctrls = controls.All().Where(c => c.GetType() == typeof(Button));

3 Responses to “Using Linq to Find a Control”

  1. Ewerton says:

    So, you will “walk” across every page control?
    How about the performance of your code?

  2. [...] This post was mentioned on Twitter by Ewerton Mattos, LINQ Feeds. LINQ Feeds said: Using Linq to Find a Control | Naresh.Jois http://bit.ly/bgalyZ [...]

  3. naresh says:

    The performance is quite ok actually, and the control tree is anyaway loaded thus there will be no reload of control tree.

Leave a Reply