Writing Custom LINQ Extension Methods

Microsoft have done a great job with LINQ IMHO. However there are times when it might be handy to create your own LINQ extension methods. LINQ extension methods can be applied to any type provided that the source is of type IEnumerable<T>, so thats really the only requirement.

So how do we write an extension method. Well its quite simple. Here are 2 that I’ve written for a  IEnumerable<string> the first example takes a Predicate and the second one doesnt. This extension method will check whether a file name string is a valid image file, but you can do it for whatever your pupose is.

customlinq.png

The only other thing to note is the cryptic “this” keyword used in the method signature. This means its being applied to the current IEnumerable<T> collection. Just always put it in your extension methods and you’ll be fine.

So how to use these extension methods, well providing your dealing with a  Enumerable<string> collection youll get the option coming up as an extension method.

vs2008linq.png

And to actually use it you could use a standard LINQ query something like

usingcustomlinq.png

Advertisements

3 thoughts on “Writing Custom LINQ Extension Methods

  1. axa says:

    Files.Where(x=>x.Contains(“.bmp”)) etc does the same.

  2. sacha says:

    Yeah sure, but that would not have made a very good post on extension methods now would it 🙂

  3. FFFFFFFUUUUUUUUUUUU says:

    thanks for the great post!

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

%d bloggers like this: