265

LINQ is one of the greatest improvements to .NET since generics and it saves me tons of time, and lines of code. However, the fluent syntax seems to come much more natural to me than the query expression syntax.

var title = entries.Where(e => e.Approved)
    .OrderBy(e => e.Rating).Select(e => e.Title)
    .FirstOrDefault();

var query = (from e in entries
             where e.Approved
             orderby e.Rating
             select e.Title).FirstOrDefault();

Is there any difference between the two or is there any particular benefit of one over other?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
JarrettV
  • 18,845
  • 14
  • 46
  • 43
  • 1
    For complex queries, I find lambda syntax more understandable/readable, but query syntax just simply prettier. – nawfal Aug 01 '15 at 09:27

14 Answers14

266

Neither is better: they serve different needs. Query syntax comes into its own when you want to leverage multiple range variables. This happens in three situations:

  • When using the let keyword
  • When you have multiple generators (from clauses)
  • When doing joins

Here's an example (from the LINQPad samples):

string[] fullNames = { "Anne Williams", "John Fred Smith", "Sue Green" };

var query =
  from fullName in fullNames
  from name in fullName.Split()
  orderby fullName, name
  select name + " came from " + fullName;

Now compare this to the same thing in method syntax:

var query = fullNames
  .SelectMany (fName => fName.Split().Select (name => new { name, fName } ))
  .OrderBy (x => x.fName)
  .ThenBy  (x => x.name)
  .Select  (x => x.name + " came from " + x.fName);

Method syntax, on the other hand, exposes the full gamut of query operators and is more concise with simple queries. You can get the best of both worlds by mixing query and method syntax. This is often done in LINQ to SQL queries:

var query =
  from c in db.Customers
  let totalSpend = c.Purchases.Sum (p => p.Price)    // Method syntax here
  where totalSpend > 1000
  from p in c.Purchases
  select new { p.Description, totalSpend, c.Address.State };
Joe Albahari
  • 30,118
  • 7
  • 80
  • 91
  • 2
    Nice answer. Can you tell me a little bit more about what ".Select (name => new { name, fName } )" is doing? – quillbreaker Aug 10 '10 at 12:34
  • 12
    It selects the individual word (anne, williams, john, etc) along with the full name in an anonymous type. This allows you to "carry" the original full name so that you have access to both the full name and individual word in the rest of the query. – Joe Albahari Aug 11 '10 at 02:41
59

I prefer to use the latter (sometimes called "query comprehension syntax") when I can write the whole expression that way.

var titlesQuery = from e in entries
                  where e.Approved
                  orderby e.Rating
                  select e.Titles;

var title = titlesQuery.FirstOrDefault();

As soon as I have to add (parentheses) and .MethodCalls(), I change.

When I use the former, I usually put one clause per line, like this:

var title = entries
    .Where (e => e.Approved)
    .OrderBy (e => e.Rating)
    .Select (e => e.Title)
    .FirstOrDefault();

I find that a little easier to read.

Jay Bazuzi
  • 45,157
  • 15
  • 111
  • 168
29

Each style has their pros and cons. Query syntax is nicer when it comes to joins and it has the useful let keyword that makes creating temporary variables inside a query easy.

Fluent syntax on the other hand has a lot more methods and operations that aren't exposed through the query syntax. Also since they are just extension methods you can write your own.

I have found that every time I start writing a LINQ statement using the query syntax I end up having to put it in parenthesis and fall back to using fluent LINQ extension methods. Query syntax just doesn't have enough features to use by itself.

geppy
  • 604
  • 8
  • 10
James Newton-King
  • 48,174
  • 24
  • 109
  • 130
  • "since they are just extension methods you can write your own." -- would you run into this problem? http://stackoverflow.com/a/3850254/1175496 – Nate Anderson Sep 20 '16 at 12:46
23

In VB.NET i very much prefer query syntax.

I hate to repeat the ugly Function-keyword:

Dim fullNames = { "Anne Williams", "John Fred Smith", "Sue Green" };
Dim query =
     fullNames.SelectMany(Function(fName) fName.Split().
     Select(Function(Name) New With {Name, fName})).
     OrderBy(Function(x) x.fName).
     ThenBy(Function(x) x.Name).
     Select(Function(x) x.Name & " came from " & x.fName)

This neat query is much more readable and maintainable in my opinion:

query = From fullName In fullNames
        From name In fullName.Split()
        Order By fullName, name
        Select name & " came from " & fullName

VB.NET's query syntax is also more powerful and less verbose than in C#: https://stackoverflow.com/a/6515130/284240

For example this LINQ to DataSet(Objects) query

VB.NET:

Dim first10Rows = From r In dataTable1 Take 10

C#:

var first10Rows = (from r in dataTable1.AsEnumerable() 
                   select r)
                   .Take(10);
Community
  • 1
  • 1
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • 12
    My sympathies for those VB developers who cant use query style. – nawfal Mar 06 '14 at 17:14
  • 1
    Your last C# example is too simplistic to be valuable: you would simply write `dataTable1.AsEnumerable().Take(10); – Emyr Nov 18 '16 at 10:15
  • @Emyr: my last paragraph which begins with "VB.NET's query syntax is also more powerful and less verbose than in C#" is just comparing VB.NET's query syntax with C#, you are using method syntax. – Tim Schmelter Nov 18 '16 at 10:22
18

I don't get the query syntax at all. There's just no reason for it in my mind. let can be acheived with .Select and anonymous types. I just think things look much more organized with the "punctuation" in there.

Instance Hunter
  • 7,837
  • 5
  • 44
  • 56
  • 10
    Multiple joins can get quite laborious quite quickly with the fluent syntax. I do generally use fluent myself though - unless joins are involved. – Roman Starkov May 04 '10 at 18:11
  • 1
    @Instance Hunter: Same here. It took me quite a while to start to grasp the idea of fluent syntax. In combination with the powerful enumerable and the idea of "pure" functions, I now really enjoy it, and formerly tricky situations that had no nice code representation. For ye-ole-SQL-part of the brain, it's still a bless to have query syntax. – Xan-Kun Clark-Davis Feb 26 '17 at 10:53
13

The fluent interface if there's just a where. If I need a select or orderby, I generally use the Query syntax.

James Curran
  • 101,701
  • 37
  • 181
  • 258
9

Fluent syntax does seem more powerful indeed, it should also work better for organizing code into small reusable methods.

Kozyarchuk
  • 21,049
  • 14
  • 40
  • 46
5

I know this question is tagged with C#, but the Fluent syntax is painfully verbose with VB.NET.

Larsenal
  • 49,878
  • 43
  • 152
  • 220
4

I really like the Fluent syntax and I try to use it where I can, but in certain cases, for example where I use joins, I usually prefer the Query syntax, in those cases I find it easier to read, and I think some people are more familiar to Query (SQL-like) syntax, than lambdas.

Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838
4

While I do understand and like the fluent format , I've stuck to Query for the time being for readability reasons. People just being introduced to LINQ will find Query much more comfortable to read.

LizB
  • 2,193
  • 16
  • 17
4

I prefer the query syntax as I came from traditional web programming using SQL. It is much easier for me to wrap my head around. However, it think I will start to utilize the .Where(lambda) as it is definitely much shorter.

Steve T
  • 7,729
  • 6
  • 45
  • 65
4

I've been using Linq for about 6 months now. When I first started using it I preferred the query syntax as it's very similar to T-SQL.

But, I'm gradually coming round to the former now, as it's easy to write reusable chunks of code as extension methods and just chain them together. Although I do find putting each clause on its own line helps a lot with readability.

Appulus
  • 18,630
  • 11
  • 38
  • 46
Antony Scott
  • 21,690
  • 12
  • 62
  • 94
3

I have just set up our company's standards and we enforce the use of the Extension methods. I think it's a good idea to choose one over the other and don't mix them up in code. Extension methods read more like the other code.

The comprehension syntax does not have all operators and using parentheses around the query and add extension methods after all just begs me for using extension methods from the start.

But for the most part it is just personal preference with a few exceptions.

Rodi
  • 388
  • 2
  • 9
3

From Microsoft's docs:

As a rule when you write LINQ queries, we recommend that you use query syntax whenever possible and method syntax whenever necessary. There is no semantic or performance difference between the two different forms. Query expressions are often more readable than equivalent expressions written in method syntax.

https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/#query-expression-overview

They also say:

To get started using LINQ, you do not have to use lambdas extensively. However, certain queries can only be expressed in method syntax and some of those require lambda expressions.

https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/query-syntax-and-method-syntax-in-linq