The powerful Extension Methods due to LINQ have made our development really simple and easy. However in some cases these methods are not available as depicted in the following screenshot.
Here are a few scenarios in which we may find our extension methods missing:
- Iterating through all the controls in a Windows Form (or any other container control) via their Controls collection
- Iterating through items in our classic non-generic collections (e.g. ArrayList) under System.Collections namespace
- Iterating through Columns in a DataGridView control
- Iterating through Matches while working with Regular expressions
- Retrieving enumeration values via Enum.GetValues
The reason is that all the above collections implement IEnumerable (a non-generic interface) while our LINQ extension methods are defined for IEnumerable<T>. Luckily, things are simple to work out in this case; we have two extension methods Cast and OfType that return an IEnumerable<T> from IEnumerable. As the name suggests, Cast is used to cast all the objects to a type while OfType filters and extracts out elements of a particular type.
So, with this, here’s an example that grabs all the TextBoxes from a Windows Form and checks if anyone is empty.
var emptyTextboxes = from t in this.panel1.Controls.OfType<TextBox>() where t.Text == string.Empty select t; if (emptyTextboxes.Any()) MessageBox.Show("Atleast one textbox is empty");