LINQ: query syntax

A query is a statement

LINQ is a set of methods on IEnumerable<T> (Where, Select, OrderBy and about seventy more), plus a second way to write a call to them: from x in source where ... select .... The query form is not a separate language bolted onto C#: the compiler translates every query into the same method calls, and a type becomes queryable by having those methods. That is why a query works over an array, a List<T>, a database table or a JSON document, as long as something implements the methods.

The first program filters an array of strings, sorts it and prints it:

var cities = new[] { "Oslo", "Lima", "Kyiv", "Rome", "Baku", "Pune", "Cork" }; var shortNames = from city in cities where city.Length == 4 orderby city select city; foreach (var city in shortNames) { Console.WriteLine(city); } Console.WriteLine($"count: {shortNames.Count()}");

dotnet run

Baku
Cork
Kyiv
Lima
Oslo
Pune
Rome
count: 7

Seven cities have four letters, so nothing was filtered out and orderby city alone did the work: the result is in ordinal order, which for ASCII names is alphabetical. Count() on the query is a second call, not a stored number, and it walks the source again; that is the first thing the part on deferred execution unpacks.

where, orderby and select

The three clauses are the shape of most queries:

The second program uses all of them over a list of tuples and projects a new shape, a double computed from the Celsius value:

var temps = new List<(string City, int Celsius)> { ("Oslo", 4), ("Lima", 24), ("Kyiv", 7), ("Rome", 18), ("Baku", 14), }; var warm = from t in temps where t.Celsius >= 10 orderby t.Celsius descending, t.City select new { t.City, t.Celsius, Fahrenheit = t.Celsius * 9 / 5 + 32 }; foreach (var item in warm) { Console.WriteLine($"{item.City,-6}{item.Celsius,4} C {item.Fahrenheit,5} F"); } Console.WriteLine($"warm cities: {warm.Count()}");

dotnet run

Lima 24 C 75 F
Rome 18 C 64 F
Baku 14 C 57 F
warm cities: 3

{item.City,-6} left-aligns the name in six columns and {item.Fahrenheit,5} right-aligns the number in five, so the table lines up without a library. The integer arithmetic t.Celsius * 9 / 5 + 32 is exact for these values, which is why no double appears: 14, 18 and 24 stay whole numbers through the whole conversion.

The order of the clauses is not free: from first (or a from per source, which comes later in the course), then where, orderby, and select or group last. The compiler names the clause that is out of place in the error, and the error points at that clause, not at the query as a whole.

let and a computed value

let introduces a name for an intermediate value, so the next clauses can use it instead of repeating the expression. The variable is in scope in every clause after it, and a let that is only used once is usually a sign that the expression belonged in the select.

The third program uses it for the first letter, which the orderby and the group clauses of the next part both read; written twice it would be two expressions that a reader has to compare by eye:

var words = new[] { "apple", "avocado", "banana", "cherry", "apricot", "blueberry" }; var byLetter = from word in words let letter = word[0] orderby letter group word by letter into letterGroup select new { Letter = letterGroup.Key, Words = letterGroup.Count() }; foreach (var entry in byLetter) { Console.WriteLine($"{entry.Letter}: {entry.Words}"); } Console.WriteLine($"letters: {byLetter.Count()}");

dotnet run

a: 3
b: 2
c: 1
letters: 3

Three words start with a, two with b, one with c. The into after group is the continuation: it names the group and lets the query go on with a select, which a query without into cannot do.

group by

group item by key produces a sequence of groups, and every group is an IGrouping<TKey, TElement>: a Key and the items that share it. Grouping is the one clause with no direct equivalent in the method form of the same query that reads as well, which is why query syntax stays in use for reports.

A group can also carry a whole object, not only a count:

var people = new[] { ("Anna", "Kyiv"), ("Borys", "Lima"), ("Clara", "Kyiv"), ("Danylo", "Rome"), ("Elena", "Lima"), }; var byCity = from person in people group person by person.Item2 into city orderby city.Key select city; foreach (var city in byCity) { var names = string.Join(", ", city.Select(p => p.Item1)); Console.WriteLine($"{city.Key}: {names}"); } Console.WriteLine($"cities: {byCity.Count()}");

dotnet run

Kyiv: Anna, Clara
Lima: Borys, Elena
Rome: Danylo
cities: 3

The group is a sequence itself, so city.Select(...) walks it inside the loop: the method form works on a group exactly as it works on an array. city.Key is the tuple field the grouping used, and the order of the groups inside a city is the order of the source, because grouping is stable and this query only sorts the groups.

A query is not a result yet

Every program above builds the query and then walks it once with foreach. Nothing in the query runs before that: the query object holds the source and the steps, and the first walk is the first read of the data. Two walks read it twice, which is measured in the lesson on deferred execution, and it explains why a query over a list that changed after the query was written sees the new items.

Exercises

  1. Add a second where clause and a descending sort to the first program. Which numbers appear, and in what order?
  2. Replace the anonymous type of the second program with a named record and keep the query working.
  3. Group the words of the third program by length instead of by first letter.
  4. Write the same query twice, once in query syntax and once with the methods, and compare the two results with SequenceEqual.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does the compiler do with a query expression?

    Answer

    Translates it into calls to Where, Select, OrderBy and the other methods

    Query syntax is syntactic sugar over the LINQ methods, which the compiler emits as ordinary calls.

  2. Which clause must come first in a query with one source?

    Answer

    from

    The from clause names the range variable every later clause uses, so it opens the query.

  3. What is the type of one group in the result of group word by letter?

    Answer

    IGrouping<char, string>: a Key and the matching items

    Grouping yields IGrouping<TKey, TElement>, which exposes Key and is itself a sequence of the elements.

  4. What does this program print? var cities = new[] { "Oslo", "Lima", "Rome" }; var q = from c in cities where c.Length == 4 select c; Console.WriteLine(string.Join(",", q));

    Answer

    Oslo,Lima,Rome

    Oslo, Lima and Rome all have four letters, so the filter keeps all three in source order.

  5. What does let word = x * 2 do in a query?

    Answer

    Names an intermediate value that later clauses can use

    let introduces a range variable for a computed value, in scope for the clauses that follow it.

  6. When does a query over an array read the array?

    Answer

    When the query is enumerated, not when it is written

    Query operators are lazy: the source is read when the result is walked, so a later change to the source is seen.

  7. What does orderby a, b descending mean?

    Answer

    Sort ascending by a, and within equal a by b descending

    The first key is the primary sort and the second is the tie-breaker, and descending applies to the key it follows.

  8. What is wrong with a query whose last clause is where?

    Answer

    A query must end with select or group

    The compiler reports CS0747 here: the select or group clause that produces the result is missing.

  9. What does into letterGroup after a group clause allow?

    Answer

    Continuing the query with a select over the groups

    A group into continuation names the group sequence so later clauses can project or filter it.

  10. Which sentence about query and method syntax is true?

    Answer

    Every query expression has an equivalent chain of method calls

    The two forms compile to the same calls, so the choice between them is about what reads better.

The code on this page was built with the .NET SDK 10.0.303 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev