Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / LINQ

Writing Custom LINQ Extension Methods

5.00/5 (5 votes)
17 Jun 2009CPOL 48.4K  
How to write custom LINQ extension methods

Microsoft has 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 that's really the only requirement.

So how do we write an extension method. Well it's quite simple. Here are 2 that I’ve written for an IEnumerable<string> - the first example takes a Predicate and the second one doesn't. 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.

37373/customlinq.png

The only other thing to note is the cryptic “this” keyword used in the method signature. This means it's 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, you'll get the option coming up as an extension method.

37373/vs2008linq.png

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

37373/usingcustomlinq.png

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)