LINQ in Action - LINQ Book & News

Converting LINQ queries from query syntax to method/operator syntax

Yesterday a reader of the LINQ in Action book posted an interesting challenge on the book's forum. It's interesting enough to be reposted it here.

The request was to convert a LINQ query expression (query syntax) to a query operator call chain (method syntax or dot notation). The original query was the following one:

from publisher in SampleData.Publishers
join book in SampleData.Books on publisher equals book.Publisher into publisherBooks
from book in publisherBooks.DefaultIfEmpty()
select new
  Publisher = publisher.Name,
  Book = book == default(Book) ? "(no books)" : book.Title

This query comes from LINQ in Action. In chapter 4 more precisely, where we cover grouping and joins.

Converting LINQ queries is an interesting exercise because it's not always easy to find the solution but you learn a lot in the process. Often, you'll have to use "tricks". Here the tricks are based on the use of anonymous types. Side note: this is also what you'd use to translate the let keyword.

Here is the solution I gave:

    publisher => publisher, book => book.Publisher,
    (publisher, publisherBooks) => new { Publisher = publisher, PublisherBooks = publisherBooks })
    group => group.PublisherBooks.DefaultIfEmpty<Book>(),
    (group, book) => new {
      Publisher = group.Publisher.Name,
      Book = (book == null) ? "(no books)" : book.Title

Not as easy to read as your original query, don't you think? See my previous post about Query syntax vs. Method syntax to decide which syntax is best for you.

"How did he manage to convert the query," you may be wondering... Well, even if I know the tricks, the easiest is to use .NET Reflector to decompile the IL.
If you specify ".NET 3.5" for the Optimization option, you'll see the query expression. But if you specify ".NET 2.0", you'll see something that looks close to the above query. You'll have to replace the anonymous methods with lambda expressions and change the name of the anonymous parameters to make the code somewhat more readable, though.

As usual, Reflector is your best friend. It reveals a lot of secrets ;-)

Update: Joe Albahari, of LINQPad fame, suggested other solutions:

1) Calling .ToString() on the query's expression will work just fine if you add AsQueryable() to the first sequence: from publisher in SampleData.Publishers.AsQueryable() join book...
2) If you use LINQPad to run the query, you'll notice it shows lambda translations for all IQueryable-based queries. LINQPad uses its own expression visitor so the result is much more readable than simply calling ToString on the expression.

Published Friday, February 6, 2009 6:05 PM by Fabrice Marguerie


No Comments
New Comments to this post are disabled