Making Enumerable Collections LINQ-Queryable

LINQ is one of the greatest things that’s happened to Windows programming. I love it, and I use it all the time.

Occasionally, you’ll run into an enumerable collection class that can’t be queried with LINQ because it isn’t associated with a type. This can be easily overcome by using the Enumerable.Cast<T>() method.

Here’s a quick example from MSDN:

System.Collections.ArrayList fruits = new System.Collections.ArrayList();
fruits.Add("apple");
fruits.Add("mango");

IEnumerable query =
	fruits.Cast().Select(fruit => fruit);

foreach (string fruit in query)
{
	Console.WriteLine(fruit);
}

This is a great technique to use instead of settling and using a for-each loop (ick!).

Advertisement

Author: Adam Prescott

I'm enthusiastic and passionate about creating intuitive, great-looking software. I strive to find the simplest solutions to complex problems, and I embrace agile principles and test-driven development.

One thought on “Making Enumerable Collections LINQ-Queryable”

Leave a comment

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 )

Facebook photo

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

Connecting to %s

%d bloggers like this: