Extension Methods and Lambda Expressions Revisited

Before I break down the elements of a LINQ expression in more detail, I want to show you an alternate way of getting the work done. In fact, it’s more or less what the compiler is doing under the covers. The LINQ syntax is very foreign looking in a predominantly imperative language like C#. It’s easy to jump to the conclusion that the C# language underwent massive modifications in order to implement LINQ. Actually, the compiler simply transforms the LINQ expression into a series of extension method calls that accept lambda expressions.

If you look at the System.Linq namespace, you’ll see that there are two interesting static classes full of extension methods: Enumerable and Queryable. Enumerable defines a collection of generic extension methods usable on IEnumerable types, whereas Queryable defines the same collection of generic
extension methods usable on IQueryable types. If you look at the names of those extension methods, you’ll see they have names just like the clauses in query expressions. That’s no accident because the extension methods implement the standard query operators I mentioned in the previous section. In fact, the query expression in the previous example can be replaced with the following code:
<pre class="brush:csharp">
var query = employees
.Where( emp => emp.Salary > 100000 )
.OrderBy( emp => emp.LastName )
.OrderBy( emp => emp.FirstName )
.Select( emp => new {LastName = emp.LastName,
FirstName = emp.FirstName} );
</pre>
Notice that it is simply a chain of extension method calls on IEnumerable, which is implemented by employees. In fact, you could go a step further and flip the statement inside out by removing the extension method syntax and simply call them as static methods, as shown here:
<pre class="brush:csharp">
var query =
Enumerable.Select(
Enumerable.OrderBy(
Enumerable.OrderBy(
Enumerable.Where(
employees, emp => emp.Salary > 100000),
emp => emp.LastName ),
emp => emp.FirstName ),
emp => new {LastName = emp.LastName,
FirstName = emp.FirstName} );
</pre>
But why would you want to do such a thing? I merely show it here for illustration purposes so you know what is actually going on under the covers. Those who are really attached to C# 2.0 anonymous methods could even go one step further and replace the lambda expressions with anonymous methods. Needless to say, the Enumerable and Queryable extension methods are very useful even outside the context of LINQ. And as a matter of fact, some of the functionality provided by the extension methods does not have matching query keywords and therefore can only be used by invoking the extension methods directly.


Source Of Information : Apress Accelerated C Sharp 2010

0 comments


Subscribe to Developer Techno ?
Enter your email address:

Delivered by FeedBurner