When to use C# LINQ with Query Syntax over Method Syntax

When to use C LINQ with Query Syntax over Fluent Syntax

LINQ is awesome, right? It’s one of those things everyone loves from first sight. Like smartphones in the early days – you just know it’s right.

For this post, I’ll assume you already know LINQ, use it and love it.

LINQ comes in two flavors – the Query Syntax and Method Syntax (aka Fluent Syntax). For example, the following is the same:

For some reason, most developers (including myself) feel much more comfortable with Method Syntax. I can’t explain it fully, but I think the reason is that programmers are used to regular method calls. Unlike query-syntax, which is sort of a new language (well, kind of like SQL but still much less familiar than C#).

There isn’t any distinct advantage of one over the other. In fact, any query syntax can be transformed into method syntax (See Dudi Keleti’s automatic Roslyn converter).

However, method-syntax isn’t always a better syntax. There are several cases where query syntax is better, and this is what this post is all about. By better, I mean it makes more readable code. You’ll see some cool examples where method-syntax creates pretty complicated code that can be replaced by a short and neat query-syntax expression.

The awesome ‘let’ keyword

One of the nicest things about the query-syntax is the [su_highlight class=”inline”]let[/su_highlight] keyword. It allows to store a result for later use in the query. Here’s an example:

As you can see, with query syntax everything is nice and clean. Method-syntax isn’t terrible, but it requires you to create anonymous classes and use those for the rest of the query.

So whenever you want to “save” a value in addition to the queried collection, consider using the [su_highlight class=”inline”]let[/su_highlight] clause.

Multiple data sources

If you have several data sources for the query, the query-syntax is probably a better choice. The reason is that you can use the [su_highlight class=”inline”]from[/su_highlight] keyword several times. For example:

The purpose here is to get a collection with all the possible combinations from 2 sources. With query-syntax, the code is simple and self-explanatory. The method-syntax, on the other hand, requires a head-scratching to understand.

To understand how both ways work to give the same result, you can use the OzCode VS extension’s LINQ feature:

OrderBy with multiple orderings

In both query-syntax and method-syntax, you can easily perform multiple orderings. For example, we can order people by Age and then Income, where Age is the first ordering and Income the second one. This means that people with the same Age will be ordered by Income.

I admit, both syntaxes are good and the difference is not as big as in the other cases. But query-syntax is still nicer.

GroupBy vs group

The [su_highlight class=”inline”]GroupBy[/su_highlight] extension method of method-syntax is pretty similar to [su_highlight class=”inline”]group[/su_highlight] in query-syntax. For example:

The method-syntax is a bit unclear. What does the second parameter stand for? Sure, once you think about it a bit, it becomes clearer. But I don’t want to think when I’m looking at code, I want to read it like a book. A children’s book if possible.

Joins are fun with query-syntax

Well, maybe joins are never truly fun, but they are much nicer with query-syntax. Here is inner join for example:

In the method-syntax way, the 2nd and 3rd parameters of [su_highlight class=”inline”]Join[/su_highlight] are compared. But unlike in query-syntax, it’s not really clear from the code. In query-syntax it’s much clearer with
[su_highlight class=”inline”]join prod in products on category.ID equals prod.CategoryID[/su_highlight]

As a rule of thumb, whenever you need to Join collections, the query-syntax is going to be better. And by better I mean more readable and easier code.

Summary

In most cases, with simple operators like [su_highlight class=”inline”]Where[/su_highlight], [su_highlight class=”inline”]Select[/su_highlight] and [su_highlight class=”inline”]OrderBy[/su_highlight] the method-syntax is great. It provides an easy-to-understand functional syntax. You can switch to query-syntax for those, but I don’t recommend it. Even if you get used to it, remember that most programmers still find method-syntax more readable.

In some special cases, like the ones described above, query-syntax can be better. Those cases are:

  • Multiple data sources
  • “Saving” values for later in the query (‘let’ keyword)
  • Order-By with multiple orders
  • Group-By’s
  • Joins

As I said in the beginning, there’s no distinct advantage of one syntax over the other besides readability. There’s even a cheat sheet if you want to convert between them.

Share:

Enjoy the blog? I would love you to subscribe! Performance Optimizations in C#: 10 Best Practices (exclusive article)

12 thoughts on “When to use C# LINQ with Query Syntax over Method Syntax”

  1. > var methodSyntax = names
    > .GroupBy(name => name[0], name => name);

    Personally I prefer writing this way:

    var methodSyntax = names
    .GroupBy(name => name[0]);

    The result is the same but more readable and closer to the query form.

    1. Technically “Query Form” does not exist as a language and it is only a syntactic sugar. Compiler translates Query form into the same Method Call Chain form. That said there may be some cases where compiler might not translate Query form into a method syntax in an optimal form causing some unnecessary intermediate steps or choosing a more expensive solution to achieve the same result.

      I do not have a specific example of that though because I’ve encountered that many years ago, but it is one of the reasons why I stick to method chain syntax. Another reason is because query form can only do maybe half the stuff method syntax can and it feels very ugly trying to mix them.

  2. I have a more practical distinction, based on what kind of code you are writing. Not surprisingly, query syntax works a lot better for making queries to providers using SQL, the biggest advantage being join and let that you mentioned.

  3. leszekpietrzakfluentmoney

    Thanks.
    Could add nice sample with many joins Inner and left to see the huge difference in syntaxes.

Comments are closed.