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:
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:
.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:
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:
.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.
Cross-posted from http://linqinaction.net