LINQ vs. XQuery
.NET 2.0 Book Package - 3600 Pages!

LINQ Part 5 - Custom Extension Methods

Part 4 of this series showed how the following query expression resolves to methods.

var winners = from r in racers
   where r.Wins > 3
   orderby r.Wins descending
   select r;

Part 5 of this series show how to use custom extension methods with query expressions.

All the parts of the query expression can be overridden with custom extension methods. The where part of the query expression resolves to the Where extension method. The following method implementation demonstrates a custom extension method to be used with objects that implement IEnumerable<Racer>:

namespace

UseCustomWhere
{
  
public static class Algorithm
  
{
     
public static IEnumerable<Racer> Where(
           
this IEnumerable<Racer> racers,
           
Func<Racer, bool> predicate)
     
{
        
foreach (Racer r in racers)
        
{
           
Console.WriteLine("checking {0}", r.Name);
           
if (predicate(r))
              
yield return r;
        
}
     
}
  
}
}

An extension method is a static method that requires the this keyword with the first parameter. This way every object of type of the first parameter can be used to invoke the method. A previous example of an extension method demonstrated an extension to the String class.

Extension methods don't break access rules of object-orientation. Extension methods are just a different way to invoke static methods. The extension method does not have access to private or protected member of the class that is extended.

To use the extension method from the query expression, the method just has to be brought into the scope. Opening the namespace (in the example UseCustomWhere), uses the extension method Where with the query expression.

Christian

Comments

Feed You can follow this conversation by subscribing to the comment feed for this post.

thomas sabo

Finally found what I want, I'm a beginner content inside of great help to me with you, share

Monster LadyGaga

The composition of very good. Give me a lot of help, gave me a big inspiration! Hope to continue trying to write something better!

Verify your Comment

Previewing your Comment

This is only a preview. Your comment has not yet been posted.

Working...
Your comment could not be posted. Error type:
Your comment has been posted. Post another comment

The letters and numbers you entered did not match the image. Please try again.

As a final step before posting your comment, enter the letters and numbers you see in the image below. This prevents automated programs from posting comments.

Having trouble reading this image? View an alternate.

Working...

Post a comment

Your Information

(Name and email address are required. Email address will not be displayed with the comment.)