Tuesday, 3 February 2009

Use LINQ to extract objects from a collection by type

Language INtegrated Query (LINQ) was introduced to the .NET Framework in version 3.5, which allows the developer to perform SQL-like queries against collections of objects in their code.

LINQ includes a method called OfType that allows you to return objects of a given type from a collection.  For example, say you wanted to disable all text boxes in your Windows Forms application.  The pre-LINQ way would require you to iterate through all of the items in the Form object's Controls collection, setting the Enabled property of each text box as you go.  Obviously, if your form contains lots of different controls this can be very inefficient, but now with LINQ you can do the following in C#:

using System.Linq;

// Use the LINQ OfType method to extract all text boxes from the form's Controls collection
IEnumerable<TextBox> textBoxes = this.Controls.OfType<TextBox>();
foreach (TextBox tb in textBoxes)
    // Disable this text box
    tb.Enabled = false;