Click here to Skip to main content
15,945,119 members
Articles / LINQ

Writing Custom LINQ Extension Methods

Rate me:
Please Sign up or sign in to vote.
5.00/5 (5 votes)
17 Jun 2009CPOL 48.1K   13   3
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.


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.


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



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

Written By
Software Developer (Senior)
United Kingdom United Kingdom
I currently hold the following qualifications (amongst others, I also studied Music Technology and Electronics, for my sins)

- MSc (Passed with distinctions), in Information Technology for E-Commerce
- BSc Hons (1st class) in Computer Science & Artificial Intelligence

Both of these at Sussex University UK.


I am lucky enough to have won a few awards for Zany Crazy code articles over the years

  • Microsoft C# MVP 2016
  • Codeproject MVP 2016
  • Microsoft C# MVP 2015
  • Codeproject MVP 2015
  • Microsoft C# MVP 2014
  • Codeproject MVP 2014
  • Microsoft C# MVP 2013
  • Codeproject MVP 2013
  • Microsoft C# MVP 2012
  • Codeproject MVP 2012
  • Microsoft C# MVP 2011
  • Codeproject MVP 2011
  • Microsoft C# MVP 2010
  • Codeproject MVP 2010
  • Microsoft C# MVP 2009
  • Codeproject MVP 2009
  • Microsoft C# MVP 2008
  • Codeproject MVP 2008
  • And numerous codeproject awards which you can see over at my blog

Comments and Discussions

GeneralTnx Pin
Bostjan Gajsler29-Apr-11 0:29
Bostjan Gajsler29-Apr-11 0:29 
GeneralExtension method error Pin
wilfredogr16-Mar-11 4:00
wilfredogr16-Mar-11 4:00 
GeneralSome comments... Pin
Oleg Shilo17-Jun-09 14:41
Oleg Shilo17-Jun-09 14:41 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.