How LINQ Works

Assuming that you understood the concept of having syntax to integrate queries into a language, may want to see how this works. When you write the following code:
Customer[] Customers = GetCustomers();
var query =
from c in Customers
where c.Country == "Italy"
select c;
the compiler generates this code:
Customer[] Customers = GetCustomers();
IEnumerable<Customer> query =
Customers
.Where( c => c.Country == "Italy" );

From now on, we will skip the Customers declaration for the sake of brevity. When the query becomes longer, as you see here:
var query =
from c in Customers
where c.Country == "Italy"
orderby c.Name
select new { c.Name, c.City };
the generated code is longer too:
var query =
Customers
.Where( c => c.Country == "Italy" );
.OrderBy( c => c.Name )
.Select( c => new { c.Name, c.City } );

As you can see, the code apparently calls instance members on the object returned from the previous call. You will see that this apparent behavior is regulated by the extension methods feature of the host language (C# in this case). The implementation of the Where, OrderBy, and Select methods—called by the sample query—depends on the type of Customers and on namespaces specified in previous using statements. Extension methods are a fundamental syntax feature that is used by LINQ to operate with different data domains using the same syntax.

No comments:

Post a Comment