LINQ in Action - LINQ Book & News

Query syntax vs. Method syntax

In the official LINQ forum, someone asked whether it's better to use query syntax (query expression) or method syntax (dot notation).

My answer is that it's mostly a matter of tastes and it depends on the query.
If I'm writing a query that uses many query operators that aren't supported by the query syntax, then I use the method syntax. Mixing the two syntaxes in one single query can quickly make it hard to read, with all the parentheses.
If I'm writing a query that consists of only one operation, then I use the method syntax as well.
In other cases, the query syntax has advantages, like the ability to use "range" variables. The ones defined in from clauses. If you use the method syntax, then you have to redeclare the variables in each lambda expression passed as a parameter to a query operator.

Let's consider the following example:

from person in persons
where person.Age > 12
orderby person.LastName
select person.LastName;

Here, person is declared once and used in the where, orderby, and select clauses.
If you write the same query using the method syntax, you have to "redeclare" person each time in the lambda expressions:

persons
  .Where(person => person.Age > 12)
  .OrderBy(person => person.LastName)
  .Select(person => person.LastName);

Another advantage of the query syntax is the ability to use let clauses. This is really useful in complex queries or simply to avoid performing the same operation several times in a query, by storing temporary results in a variable.
Here is a sample query expression with a let clause:

from person in persons
let name = person.FirstName+person.LastName
select new { Name = name, Phones = person.Phones.Count() }

To reproduce the same using the method syntax, you have to write the following:

persons
  .Select(person => new { person = person, name = person.FirstName+person.LastName })
  .Select(x => new { Name = x.name, Phones = x.person.Phones.Count() });

Not so easy to read, don't you think? This is what the compiler generates when it encounters the above query expression, by the way.

There are other advantages to each syntax, but the ones listed above are already enough to decide which one to use in most cases.

Published Sunday, January 20, 2008 3:51 PM by Fabrice Marguerie

Comments

 

LINQ y sintaxis lambda | Climens Codelog said:

March 19, 2008 11:58 AM
 

LINQ in Action - LINQ Book & News said:

Yesterday a reader of the LINQ in Action book posted an interesting challenge on the book's forum . It's

February 6, 2009 9:08 AM
 

Fabrice's weblog said:

Yesterday a reader of the LINQ in Action book posted an interesting challenge on the book's forum . It

February 6, 2009 9:13 AM
New Comments to this post are disabled