Selecting controls using LINQ


One of my colleague asked how to get all the text boxes with no text entered in Windows form without using a For Loop. I thought of writing it with LINQ. And here is my implementation.

 var controls = from control in this.Controls
                           select control;

But this will generate a compile time error – Could not find an implementation of the query pattern for source type ‘System.Windows.Forms.Control.ControlCollection’. ‘Select’ not found. Consider explicitly specifying the type of the range variable ‘control’. But the error was self explanatory, I need to specify the type of the control. And here is the modified version.

var controls = from Control control in this.Controls
                           select control;

And if you want to select specific type of controls you need to apply a where condition.

var textboxes = from Control textbox in this.Controls
                where textbox is TextBox
                select textbox;

There is some other inbuilt operators is also available to select specific controls, like OfType()

var textboxes = from textbox in this.Controls.OfType<TextBox>()
                select textbox;

In this method we don’t need to specify the type of the control in the from statement. And one of interesting LINQ extension method is the Cast<> method, which helps to enable the standard query operators to be invoked on non-generic collections by supplying the necessary type information. You can get more information from here.

Anuraj is currently working as Technical Lead. He is a regular speaker on Technology events. He has more than 11+ years experience with Microsoft.Net Technologies.

Facebook Twitter LinkedIn Google+