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!

The comments to this entry are closed.