LINQ Interview Question #7
What is the difference between query syntax and method syntax?
LINQ Fundamentals, Syntax, IEnumerable & IQueryable Junior Beginner
Quick Interview Answer
Query syntax uses C# query keywords, while method syntax calls LINQ extension methods directly. Many query-syntax expressions are translated by the compiler into the corresponding method calls.
Detailed Explanation
Query syntax uses C# query keywords, while method syntax calls LINQ extension methods directly. Many query-syntax expressions are translated by the compiler into the corresponding method calls.
Method syntax supports the full standard query operator set and is common in production code. Query syntax can be clearer for some joins and multi-source queries. A project can use either style according to readability.
Code Example
// Query syntax
var q1 =
from p in products
where p.IsActive
select p.Name;
// Method syntax
var q2 = products
.Where(p => p.IsActive)
.Select(p => p.Name);