LINQ Part 3 - Filtering and Sorting XML
C++/CLI, Finalize and Dispose

LINQ Part 4 - What's behind a query expression?

With part 1 to 3 of this series, I've shown a query expression like the following to filter and sort data.

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

What's behind a query expression consisting of from, where, orderby descending, select? A query expression with this new C# 3.0 syntax simply resolves to methods that are invoked:

IEnumerable<Racer> winners = racers.
   Where(r => r.Wins > 3).
   OrderByDescending(r => r.Wins).
   Select(r => r);

The methods Where, OrderByDescending, Select are extension methods. Extension methods are static methods that can extend other classes.
Here is some information about how to write a custom extension method.

What about r => r.Wins > 3? This is a lambda expression that is an advancement of anonymous methods. The same code as before using extension methods and lamdba expression can be written using extension methods and anonymous methods:

IEnumerable<Racer> winners = racers.Where(
   delegate(Racer r)
   {
      return r.Wins > 3;
   }).OrderByDescending<Racer, int>(
   delegate(Racer r)
   {
      return r.Wins;
   });

The lambda expression r => r.Wins > 3 resolves to a method with the parameter r, and a body where the result from r.Wins > 3 is returned. The syntax of the lambda expression looks easier compared to anonymous methods.

More information to follow. The previous parts of this series:

Christian

Comments

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

Houston Home Security

This site is good because they give us a new thing and new ideas and new topic how good all of they are we should appreciate them because of these good thing.

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.)