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
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(
return r.Wins > 3;
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:
- LINQ Part 1 - Filtering & Sorting Object Lists
- LINQ Part 2 - Filtering & Sorting using data from the database
- LINQ Part 3 - Filtering & Sorting XML