Skip to content
Tutorials Center
My learning

Topics

Lesson 80 of 182 ยท Delegates, Events and LINQ

LINQ Query Syntax

Learn C# LINQ query syntax - from, where, select, orderby, group by, join, let and into - how it translates to method calls, and when it reads better than method syntax.

C# offers two ways to write the same LINQ query. You already know method syntax: people.Where(p => p.Age > 18).Select(p => p.Name). The other is query syntax, which looks like SQL turned around so that it starts with from:

C#
var names = from p in people
            where p.Age > 18
            select p.Name;

They are not two different technologies. The compiler rewrites every query expression into method calls before anything else happens, so both forms produce the same code, with the same deferred execution. Which one you use is about readability. Query syntax shines for joins, multiple from clauses and queries with intermediate variables; method syntax is shorter for simple filters and has operators that query syntax lacks. Most real codebases mix them.

This lesson walks through each clause, shows the translation, and gives you a rule of thumb for choosing. You should know the basics from LINQ Basics and the operators in LINQ Operators in Depth.

The shape of a query expression

A query expression starts with from and ends with select or group. In between you can place where, orderby, let, join and more from clauses.

C# from, where, orderby, select

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

  • from f in fruits declares the range variable f (one element at a time) and the source.
  • where filters, orderby sorts (use descending or ascending, and commas for tie-breakers), select produces the output.
  • The result is an IEnumerable<T>, evaluated lazily just like method syntax (see Deferred Execution).

Range variables are scoped to the query. In query syntax you write where f.Length > 3, with no lambda arrow. Behind the scenes the compiler builds the lambda f => f.Length > 3 for you.

The translation, step by step

The compiler translation is mechanical. This is what happens to the query above:

TEXT
from f in fruits                      fruits
where f.Length > 3                    .Where(f => f.Length > 3)
orderby f.Length descending, f        .OrderByDescending(f => f.Length).ThenBy(f => f)
select f.ToUpper()                    .Select(f => f.ToUpper())

Two details help when you read translated code. First, if the query ends with an identity select after other clauses (... where x > 1 select x), the compiler drops that last Select call, because it would do nothing; a query that is only from x in xs select x keeps Select(x => x) so the result is not the source object itself. Second, every range variable becomes a lambda parameter, which is why the whole query can read variables from the surrounding method, with the same capturing rules as lambdas.

select: shaping the result

select can return the element, a property, a calculation, a tuple, a record, or an anonymous type:

C# Select shapes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

let: naming an intermediate value

let introduces a new range variable computed from existing ones. It avoids repeating an expression and runs it once per element:

C# let

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

In method syntax the same thing needs an anonymous type to carry the extra value along: .Select(s => new { s, words = s.Split(' ') }).Select(x => new { x.s, x.words, count = x.words.Length }) and so on. This is the single biggest reason people prefer query syntax for multi-step queries.

Multiple from clauses

A second from iterates a collection for each element of the first, like nested loops. It translates to SelectMany:

C# Multiple from clauses

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Because both range variables stay in scope, the final select can use t and m together, which is awkward in method syntax (the SelectMany overload with a result selector).

join and join ... into

Query syntax needs no key selector lambdas; you write join x in other on a.Key equals x.Key. Note the keyword equals instead of ==, and the left key must come from the earlier range variable:

C# join and group join

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

join ... into name turns the join into a GroupJoin, and name is then the group of matches. Following it with from o in g.DefaultIfEmpty() flattens it into a left join. Query syntax has no keyword for the new LeftJoin method from .NET 10, but you can mix: (from ... ).LeftJoin(...).

Join only supports equality (equals) between keys. For compound keys use anonymous types on both sides: on new { a.X, a.Y } equals new { b.X, b.Y }.

group ... by and into

group x by key ends a query with a sequence of IGrouping<TKey, TElement>. To keep working after grouping you continue with into, which starts a new range variable (the group):

C# group by and into

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

After into g the earlier range variable s is out of scope; only g exists. This is why the where total > 400 after the grouping plays the role of SQL's HAVING: it filters groups, while a where before the group filters individual rows.

What query syntax cannot do

Query syntax covers a subset of the operators: where, select, orderby, group, join, let, multiple from. There is no keyword for Take, Skip, Distinct, First, Count, Any, ToList, Zip, Chunk, MaxBy, Union and many others. When you need them, wrap the query in parentheses and call the method, which is why you often see hybrid queries:

C# Mixing both syntaxes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

If you find yourself wrapping every second query in parentheses, method syntax throughout may read better.

Query syntax with ordering details

orderby accepts several keys with ascending (default) or descending on each. It translates to OrderBy/OrderByDescending for the first and ThenBy/ThenByDescending for the rest, so it is stable like the method versions:

C# Several orderby keys

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Query syntax is not just for collections

Because the compiler only looks for methods with the right names and shapes (Select, Where, GroupBy, ...), query syntax works on any type that provides them. LINQ to Objects uses System.Linq.Enumerable extension methods; Entity Framework uses IQueryable<T>, where the same query text is translated to SQL; you can even write your own Select on a custom type:

C# Query syntax on a custom type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

This is called the query pattern. You will rarely write it yourself, but it explains why the syntax is part of the language and not locked to IEnumerable.

Which one should you use?

Situation Prefer
Simple filter or projection (Where, Select) Method syntax: shorter
Joins, especially join ... into Query syntax: clearer
Several from clauses (nested iteration) Query syntax
Intermediate values you want to name Query syntax with let
Group, then filter and sort the groups Query syntax with into
Operators like Take, Zip, Chunk, First, Count Method syntax (or a hybrid)
Team conventions Follow them

Both compile to identical calls, so pick whichever lets the next reader see the intent fastest. Use let and join in query syntax; chain Where and Select in method syntax; and do not be afraid of the hybrid.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What must a query expression start and end with?

    A query expression begins with a from clause (the range variable and source) and ends with a select or group ... by clause.
  2. 2. How does the compiler treat from x in xs where x > 1 select x * 2?

    Query expressions are syntactic sugar. They are rewritten to method calls such as Where and Select, with the same deferred execution.
  3. 3. What does join o in orders on c.Id equals o.CustomerId into g produce?

    join ... into translates to GroupJoin. Every customer is kept, and g is the group of matching orders, which may be empty.
  4. 4. Which clause lets you compute a value once and reuse it later in the query?

    let introduces a new range variable holding a computed value, so you can reuse it in where, orderby and select without repeating the expression.
  5. 5. You need only the first three results of a query-syntax query. What do you do?

    Query syntax only covers a subset of operators. For Take, Skip, Distinct, First, Count and others you call the method on the parenthesized query.

Summary

  • Query syntax (from ... where ... select) and method syntax compile to the same method calls and are both deferred.
  • A query starts with from (range variable and source) and ends with select or group ... by.
  • let names intermediate values, extra from clauses become SelectMany, join ... equals is an inner join and join ... into a GroupJoin.
  • group x by key into g lets you continue filtering and shaping the groups, similar to SQL's HAVING.
  • Query syntax has no keywords for Take, Skip, Distinct, Count, First, ToList and more; use hybrid queries with parentheses.
  • Choose by readability: method syntax for simple chains, query syntax for joins, let and multi-source queries.

Next: LINQ Practice: Reports and Transformations