Using LINQ Methods in IList

If you haven’t heard of LINQ, it’s many things. It’s like SQL queries embedded into collections; or, it’s like closures; or, it’s like anonymous functions that you can specify. In other words, LINQ lets you perform searches on collections, like IList.

Say you had a list of “Persons”, and each Person had a LastName. You want all the people who’s last name is 3-5 characters in length. How can you do this?

IList people = ... // List();
IList shortLastNamePeople = people.Where(p => p.LastName.Length >= 3 && p.LastName.Length <= 5);

Very cool, and very, very useful. Ruby has something like this, as well, commonly used when sorting collections.

In any case, you're probably wondering why your System.Collections.Generics.IList class is somehow missing the Where (and other LINQ) methods that you see in so many samples online. The answer is both confusing and simple; all you need to do is include the LINQ namespace, like so:

using System.Linq;

Voila, the methods are automatically added to all your generic collection classes. As to why it works, I'm not sure; the System.Linq namespace is defined in the System.Core dll, but peeking inside with Reflector doesn't reveal too much information.

So if you know how it works, please drop a comment and let us know, too.

About Ashiq Alibhai, PMP

Ashiq has been coding C# since 2005. A desktop, web, and RIA application developer, he's touched ASP.NET MVC, ActiveRecord, Silverlight, NUnit, and all kinds of exciting .NET technologies. He started C# City in order to accelerate his .NET learning.
This entry was posted in Core .NET, Silverlight, Web, Wndows Forms and tagged , . Bookmark the permalink.

One Response to Using LINQ Methods in IList

  1. Matt Warren says:

    It works because the Where function is an extension method, see and for more info.

    Basically they allow you to add static methods to an existing class. But they are only syntactic sugar, they don’t really modify the calls.

Leave a Reply

Your email address will not be published. Required fields are marked *