3

I would like to know in terms of performance is there any difference between using a query syntax or method syntax (Lambda expressions) for joining two entities?

I already know that in general there are no difference in terms of result, between query syntax and method syntax. However, for joining which of these are better to use performance wise? Here is the sample code:

var queryResult = (from p in People
                       join i in Incomes
      on p.PersonId equals i.PersonId
                       select new { p.PersonId, p.Name, p.Age, i.Amount }
                      ).ToList();

        var lambdaResult = People.Join(Incomes,
                      p => p.PersonId,
                      i => i.PersonId,
                     (p, i) => new { p.PersonId, p.Name, p.Age, i.Amount }).ToList();

I have already went through these websites but nothing has been mentioned for join https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/query-syntax-and-method-syntax-in-linq

LINQ - Query syntax vs method chains & lambda

Mehdi
  • 147
  • 2
  • 9

1 Answers1

7

There is no difference. Your first version (query language) is translated lexically into the second one (method syntax) before "real" compilation. The query language is only syntactic sugar and transformed into method calls. These calls are then compiled (if possible - the translation itself does not care about the correctness of the result, e.g. if People.Join even is valid C# and there is such a Join method in whatever People might be).

There maybe a difference in that this translation uses an explicit Select call instead of the resultSelector parameter of the Join method, but even that does not measurably impact performance.

This article by Jon Skeet helped me understand the transformation from query language to method syntax.


To answer the question "What should you use": this is really up to you. Consider:

  • what is more readable/understandable to you (and your co-workers!)
  • complex queries often are more readable in query syntax, the SQL-like style can be easier to read than a long chain of method calls
  • Note that every query syntax expression can be expressed as method calls, but not all method calls can be expressed in query syntax
  • mixing both syntaxes in a single query is often more confusing than sticking to one of them
René Vogt
  • 43,056
  • 14
  • 77
  • 99