skip to content

Projection, Grouping and Joins

Select, SelectMany, GroupBy, Join, Aggregate, First vs Single, Any vs Count, plus newer CountBy and LeftJoin. Interviewers ask which operator fits a task.

on this pageshow

questions

6

In C# LINQ, when do First, FirstOrDefault, Single and SingleOrDefault each throw, and which one suits a lookup by unique key?

level: juniorimportance: must knowfreq 75%

answer

  1. zero, one or more matches
  2. OrDefault forgives only zero
  3. Single keeps reading after a match
  4. InvalidOperationException with four messages

basics

~10 s

First throws InvalidOperationException when nothing matches; FirstOrDefault returns default instead. Single also throws when a second match exists, and SingleOrDefault still throws on two matches: the OrDefault suffix forgives zero matches, never several.

solid answer

~50 s

All four live on `Enumerable` and differ on two cases. With **no** match, `First` and `Single` throw `InvalidOperationException` ("Sequence contains no matching element" for the predicate overloads) while `FirstOrDefault` and `SingleOrDefault` return `default(T)`: `null` for a reference type, `0` for an `int`, or a value you pass to the `defaultValue` overload. With **two or more** matches, `First` and `FirstOrDefault` return the first one, but `Single` and `SingleOrDefault` both throw ("Sequence contains more than one matching element"). So `Single` asserts that the data is unique and pays for it: it keeps reading after the first match to prove there is no second. For a lookup by a key that must be unique, such as an employee's email, `SingleOrDefault` states that rule and fails loudly when the data breaks it; `FirstOrDefault` is the choice when duplicates are legal and any one will do.

code

csharp · 27 lines
csharp
using System;
using System.Collections.Generic;
using System.Linq;

var staff = new List<Employee>
{
    new("Ana", "[email protected]", "Payroll"),
    new("Ben", "[email protected]", "Payroll"),
    new("Ben", "[email protected]", "Legal"),
};

Console.WriteLine(staff.First(e => e.Dept == "Payroll").Name);        // Ana
Console.WriteLine(staff.FirstOrDefault(e => e.Dept == "IT") is null); // True
Console.WriteLine(staff.Single(e => e.Email == "[email protected]").Name); // Ana
Console.WriteLine(staff.SingleOrDefault(e => e.Email == "[email protected]") is null); // True

try { staff.SingleOrDefault(e => e.Name == "Ben"); }
catch (InvalidOperationException ex) { Console.WriteLine(ex.Message); }

try { staff.First(e => e.Dept == "IT"); }
catch (InvalidOperationException ex) { Console.WriteLine(ex.Message); }

int[] none = [];
Console.WriteLine(none.FirstOrDefault());     // 0, not null
Console.WriteLine(none.FirstOrDefault(-1));   // -1

record Employee(string Name, string Email, string Dept);

go deeper

for a junior

Recite the table: no match throws for First and Single, defaults for the OrDefault forms, and two matches throw for both Single forms. Know default is null or zero.

for a middle

Explain that Single must keep reading after its first match, name the four exception messages, and say what default(T) gives for a value type versus a reference type.

for a senior

Treat a Single exception in a log as a data-integrity signal, not a nuisance; choose the operator to encode whether a key is unique and whether absence is an error.

for a principal

Push teams to state uniqueness rules in code and storage together, so Single guards an invariant the data layer also enforces rather than masking it with FirstOrDefault.

## The four operators side by side `First`, `FirstOrDefault`, `Single` and `SingleOrDefault` are extension methods on `System.Linq.Enumerable`. Each has an overload without a predicate (look at the whole sequence) and one with a `Func<TSource, bool>` predicate (look only at matching elements). They answer the same question, "give me one element", but they disagree about what to do when the sequence holds zero or several candidates. | Operator | No match | Exactly one | Two or more | |---|---|---|---| | `First` | throws `InvalidOperationException` | returns it | returns the first | | `FirstOrDefault` | returns `default(T)` | returns it | returns the first | | `Single` | throws `InvalidOperationException` | returns it | throws `InvalidOperationException` | | `SingleOrDefault` | returns `default(T)` | returns it | throws `InvalidOperationException` | The last row is the one candidates get wrong: the **OrDefault** suffix only changes the zero-match case. `SingleOrDefault` on a sequence with two matches throws exactly like `Single`. ## The exception messages tell you which rule broke Four of the messages in the runtime's `System.Linq` resources come from these operators, each on an `InvalidOperationException`: - "Sequence contains no elements": `First()` or `Single()` without a predicate on an empty sequence. - "Sequence contains no matching element": the predicate overloads found nothing. - "Sequence contains more than one element": `Single()` or `SingleOrDefault()` without a predicate on a sequence of two or more. - "Sequence contains more than one matching element": the predicate overloads found a second match. When a production log shows the last message, the code was right to use `Single`: it has caught duplicate data, and the fix belongs in the data or in a uniqueness constraint, not in swapping the call for `First`. ## What default means `default(T)` depends on the element type: - a reference type such as a `record` or `string` gives `null`, which is why the return type is annotated `TSource?` and nullable analysis warns when you dereference it; - a value type gives its zero value: `0` for `int`, `0m` for `decimal`, a zeroed struct for a `record struct`; - the overloads `FirstOrDefault(defaultValue)` and `SingleOrDefault(predicate, defaultValue)` return the value you pass, which helps when `0` is a legal element and cannot double as "not found". An `int[]` that is empty returns `0` from `FirstOrDefault()`, indistinguishable from a real zero, so code that must tell the two apart passes a sentinel or checks `Any()` first. ## Single costs a longer scan `First` stops at the first match. `Single` cannot: after it finds a match it keeps reading the rest of the sequence to prove no second match exists, and it stops early only when it finds one and throws. On a list of 100,000 employees, `First(e => e.Email == x)` may touch one element while `Single` with the same predicate always reads all 100,000 when the data is clean. That is usually a fair price for the guarantee on an in-memory list, but it is worth knowing when the source is a large or expensive sequence. ## Choosing for a lookup 1. If the key **must** be unique and a missing key is an error, use `Single`: both failures surface as exceptions. 2. If the key must be unique but may be absent, use `SingleOrDefault` and check for `null`. 3. If several matches are legal and any one will do, or the sequence is ordered and you want the head, use `First` or `FirstOrDefault`. 4. If you look up by key many times, build a `Dictionary` or a lookup once instead of scanning with any of the four on every call. ## Common mistakes - Using `FirstOrDefault` everywhere "to be safe": duplicate rows are silently resolved by whichever came first. - Catching the exception from `First` to mean "not found" instead of calling `FirstOrDefault`. - Forgetting that `FirstOrDefault` on a value type never returns `null`. - Writing `Where(predicate).First()` and believing it costs more than `First(predicate)`; both stop at the first match.

  • Does Where(predicate).First() enumerate more than First(predicate)?
    No. `Where` is deferred and streams, so `First` pulls elements through the filter only until the first one passes, the same number of predicate calls as `First(predicate)`. The difference is a small wrapper object, not extra work over the data. The same holds for `Single`: both forms read until the end or until a second match.
  • An employee lookup by email logs "Sequence contains more than one matching element"; is switching to FirstOrDefault the fix?
    Usually not. The message comes from `Single` or `SingleOrDefault` finding a second match, which means two employees share an email the code assumed unique. Switching to `FirstOrDefault` hides the duplicate and returns whichever record happens to come first. Fix the data, enforce uniqueness where the records are created, and keep `Single` as the guard.
  • How do you tell an empty int array from one whose first element is 0 when using FirstOrDefault?
    `FirstOrDefault()` returns `0` in both cases, because `default(int)` is `0`. Pass a sentinel to the `FirstOrDefault(defaultValue)` overload, such as `-1` when salaries or ids are never negative, or test `Any()` first, or project to `int?` with `Select(x => (int?)x)` so an empty sequence yields `null`.

  • SingleOrDefault returns null when two elements match
  • Switching Single to FirstOrDefault is the fix for a duplicate-match exception
  • FirstOrDefault on an int sequence returns null when empty
  • Single stops reading as soon as it finds a match
  • Catching InvalidOperationException from First is the normal not-found check
open as a page

In C# LINQ, what does Select return when each department holds a list of employees, and how does SelectMany change that?

level: middleimportance: must knowfreq 65%

basics

~20 s

Select maps each department to one value, so selecting each department's staff list yields an IEnumerable<List<Employee>>, one list per department. SelectMany maps each department to a sequence and concatenates those sequences into one flat IEnumerable<Employee>.

open as a page

In C# LINQ, why is Any() preferred over Count() > 0 for an existence check, and when does the choice make no difference?

level: middleimportance: should knowfreq 60%

basics

~20 s

Any() stops at the first element, while Count() on a filtered or lazy sequence walks every element to finish counting. On a List<T> or array, Count() reads the Count property, so both are cheap and the property itself is clearest.

open as a page

For headcount per department in C# LINQ, how do GroupBy, ToLookup and .NET 9's CountBy differ in what they return and when they run?

level: middleimportance: should knowfreq 45%

basics

~20 s

GroupBy is deferred and yields IGrouping<TKey, TElement> groups each time it is enumerated. ToLookup runs at once and returns an ILookup you can index by key. CountBy, added in .NET 9, yields only KeyValuePair<TKey, int> counts, without building groups.

open as a page

In C# LINQ to Objects, how do you list departments with no staff, and what do Join, GroupJoin and .NET 10's LeftJoin each return?

level: middleimportance: should knowfreq 40%

basics

~20 s

Join is an inner join, so departments without staff vanish. GroupJoin yields every department with a possibly empty sequence of matches, so filter for empty groups. LeftJoin, added in .NET 10, yields each department with a null employee when nothing matches.

open as a page

A C# report finds the highest-paid employee per team with GroupBy then MaxBy; what happens on salary ties and for a team with no staff?

level: seniorimportance: should knowfreq 30%

basics

~20 s

MaxBy keeps the first element with the largest key, so ties go to whoever comes first. GroupBy groups are never empty; an empty team comes from a join, where MaxBy returns null for reference types and throws InvalidOperationException for non-nullable structs.

open as a page