There’s no accounting for taste

LINQ, a data querying feature in the .NET framework, was an absolute godsend when it arrived with .NET 3.5 a few years ago. Gone were the endless helper methods designed to manipulate or pick out bits of data from collections. In their place, an intuitive querying syntax – supported either via chaining extension methods, or by using new language constructs which provided SQL-like queries in code.

There’s been a lot of confusion about LINQ since its launch. You could argue that Microsoft didn’t help its cause by closely associating LINQ and LINQ-to-SQL. But it has been some years now, and it is quite concerning that when mentioning LINQ, most developers seem only to be aware of the database querying side of things (the confusion now lives on with LINQ-to-Entities). If only they knew the extraordinary flexibility that arbitrary query trees gave them! The provider model, coupled with deferred execution, is a truly wonderful thing.

It’s also a shame that query syntax is the way that most people seem to choose to write a LINQ query. Redmond says that query syntax is the preferred option, and they should know best, right?

In general, we recommend query syntax because it is usually simpler and more readable; however there is no semantic difference between method syntax and query syntax

But they immediately shoot themselves in the foot with the very next sentence (emphasis is mine):

…some queries, such as those that retrieve the number of elements that match a specified condition, or that retrieve the element that has the maximum value in a source sequence, can only be expressed as method calls.

So they’ve implemented some admittedly pretty syntactic sugar, but not managed to extend it to cover some common and useful parts of the new API? Frustrating!

Given the current, justified popularity, not to mention the inherent readability of, fluent interfaces, I think coding standards should prefer method syntax on these grounds alone. The only impediment I felt, when pushing myself into method syntax exclusively, was that set joining operations are less intuitive in method syntax than query syntax, for those who first learnt set joining from SQL. But I think this isn’t a good enough justification.

Method syntax for me.

Leave a Comment