LINQ: Where are my extension methods?

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");
About these ads

One Response to “LINQ: Where are my extension methods?”

  1. DotNetShoutout Says:

    LINQ: Where are my extension methods? « Mehroz’s Experiments…

    Thank you for submitting this cool story – Trackback from DotNetShoutout…


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 52 other followers

%d bloggers like this: