skip to content

In a C# query expression, what does group … by return, and why do you need into to keep querying the groups?

level: middleimportance: should knowfreq 40%

answer

  1. a sequence of keyed sequences
  2. each group exposes Key
  3. select or group must end it
  4. a continuation starts a new query
  5. earlier range variables go away

basics

~20 s

group element by key compiles to GroupBy and yields a sequence of IGrouping<TKey, TElement>, each with a Key. group ends the query, so filtering or projecting groups needs into, which starts a continuation where only the group variable is in scope.

solid answer

~40 s

`group loan.Title by loan.Author` becomes `loans.GroupBy(loan => loan.Author, loan => loan.Title)` and yields `IEnumerable<IGrouping<string, string>>`: each group is itself a sequence of titles with a `Key` property. When the element is the range variable itself, the element selector is omitted. Every query expression must end with `select` or `group` (otherwise CS0742), so `group` is the last clause, and a query that wants to filter or sort the groups adds `into overdue`. The compiler treats that as a new query over the first one, `from overdue in (…) where … select …`, so `overdue` is the only range variable left and naming `loan` after it is CS0103. `select … into` works the same way. The keyword form cannot take a custom key comparer; that needs `GroupBy` in method syntax.

code

csharp · 31 lines
csharp
using System.Linq;

var today = new DateOnly(2026, 10, 10);
Loan[] loans =
[
    new("Beloved", "Morrison", new(2026, 9, 30)),
    new("Sula", "Morrison", new(2026, 10, 2)),
    new("Things Fall Apart", "Achebe", new(2026, 10, 1)),
    new("Earthsea", "Le Guin", new(2026, 10, 20)),
];

// group ... by: ends the query; each element is an IGrouping<string, string>
IEnumerable<IGrouping<string, string>> titlesByAuthor =
    from loan in loans
    where loan.Due < today
    group loan.Title by loan.Author;

// group ... by ... into: a continuation that keeps querying the groups
var busyAuthors =
    from loan in loans
    where loan.Due < today
    group loan by loan.Author into overdue
    where overdue.Count() > 1
    select new { Author = overdue.Key, Count = overdue.Count() };

foreach (var g in titlesByAuthor)
    Console.WriteLine($"{g.Key}: {string.Join(", ", g)}");   // Morrison: Beloved, Sula / Achebe: Things Fall Apart
foreach (var row in busyAuthors)
    Console.WriteLine(row);                                   // { Author = Morrison, Count = 2 }

record Loan(string Title, string Author, DateOnly Due);

go deeper

for a junior

Recall that group … by gives a sequence of groups, each with a Key, and that you need a nested foreach to read the elements.

for a middle

Explain the translation to GroupBy with key and element selectors, the select-or-group ending rule behind CS0742, and how into starts a continuation that hides earlier range variables.

for a senior

Diagnose CS0103 after a continuation, missing key comparers in keyword form, and composite keys built from named classes without Equals overrides that silently produce one group per element.

for a principal

Treat grouping as a readability decision in shared code: continuations read well for filter-then-project reports, and method syntax is required once a comparer enters the picture.

## What group … by produces A `group` clause partitions the elements reaching it by a **key**: ```csharp from loan in loans where loan.Due < today group loan.Title by loan.Author ``` The compiler translates it into `Enumerable.GroupBy` with a key selector (`loan => loan.Author`) and an element selector (`loan => loan.Title`). When the grouped expression is just the range variable, as in `group loan by loan.Author`, the element selector is left out. The result type is `IEnumerable<IGrouping<TKey, TElement>>`, here `IEnumerable<IGrouping<string, string>>`. `IGrouping<TKey, TElement>` is an `IEnumerable<TElement>` with one extra member, `Key`. A group is therefore a sequence you enumerate, not a list you index, and reading every element of every group takes a nested loop: - the outer `foreach` walks the groups and reads `g.Key`; - the inner `foreach` walks the elements of `g`. The key can be any type: a `string`, a `bool` from a condition, a computed bucket such as `loan.Due.Year`, or a composite key written as an anonymous object, `group loan by new { loan.Author, loan.Due.Year }`, which works because anonymous types compare by value. ## Why the query has to stop there A query expression must end with a `select` clause or a `group` clause. Ending anywhere else is a syntax error, CS0742: "A query body must end with a select clause or a group clause". Without `into`, a `group` clause is therefore the query's last clause; a `where` or `orderby` cannot follow it directly. ## into: a query continuation To keep working with the groups, name them with `into`: ```csharp from loan in loans where loan.Due < today group loan by loan.Author into overdue where overdue.Count() > 1 select new { Author = overdue.Key, Count = overdue.Count() } ``` The compiler treats everything after `into` as a fresh query whose source is the query before it, as if you had written: 1. `var grouped = from loan in loans where loan.Due < today group loan by loan.Author;` 2. `from overdue in grouped where overdue.Count() > 1 select …` and then translates both parts into one chain: `Where`, `GroupBy`, `Where`, `Select`. Two consequences follow: - Only the continuation variable (`overdue`) is in scope after `into`. Referring to `loan` there fails with CS0103: "The name 'loan' does not exist in the current context". - The continuation needs its own ending `select` or `group`. `select … into` works identically: `select b.Title into t where t.Length > 8 select t.ToUpper()` continues a query over the projected values. The `into` in a `join … into` clause is a different construct; it names the per-element group of a group join. | Clause | Translation | What follows is | |---|---|---| | `group e by k` | `GroupBy(x => k, x => e)` | the end of the query | | `group e by k into g` | `GroupBy(…)` then later calls on `g` | a continuation, only `g` in scope | | `select e into v` | `Select(…)` then later calls on `v` | a continuation, only `v` in scope | | `join … into g` | `GroupJoin(…)` | the same query, `g` added beside earlier variables | ## Choosing the key and the element The two expressions in `group element by key` are independent, and each is an ordinary C# expression over the range variables in scope: - **Computed keys** bucket values: `group loan by loan.Due.Year` or `group loan by loan.Due < today` (a `bool` key that splits loans into two groups). - **Composite keys** combine values: `group loan by new { loan.Author, loan.Due.Year }` makes one group per author and year, and `g.Key.Author` reads a part back. A named class used the same way must override `Equals` and `GetHashCode`, or every element lands in its own group. - **Projected elements** shrink what each group holds: `group loan.Title by loan.Author` stores only titles, so the continuation works with strings instead of whole `Loan` objects. Because a `let` before the `group` clause is still in scope there, an expensive value can be computed once and used in both the key and the element. ## What the keywords cannot express `group … by` always uses the key type's default equality, and has no slot for an `IEqualityComparer<TKey>` such as `StringComparer.OrdinalIgnoreCase`; grouping authors' names case-insensitively needs `GroupBy(keySelector, comparer)` in method syntax. Choosing between `GroupBy`, `ToLookup`, `CountBy` and `AggregateBy` for a given job is covered with the grouping operators; this lesson covers only what the clause compiles to and how a continuation scopes names.

  • In C# query syntax, how does into after group differ from into after join?
    After `group` or `select`, `into` is a continuation: it ends the current query and starts a new one over its result, so only the new identifier is in scope. After `join`, `into` turns the join into a `GroupJoin` within the same query: the outer range variables stay in scope and the identifier names each outer element's sequence of matches.
  • How do you group by two values at once in C# query syntax?
    Use an anonymous object as the key: `group loan by new { loan.Author, loan.Due.Year } into g`. Anonymous types override `Equals` and `GetHashCode` to compare every property, so loans with the same author and year land in one group, and `g.Key.Author` and `g.Key.Year` read the parts back.

  • group … by returns a Dictionary of lists keyed by the group key.
  • A where clause can follow a group clause without into.
  • After group … into g, the original range variable is still usable.
  • group … by in query syntax compiles to ToLookup.
  • A query expression may end with a where or orderby clause.