skip to content

LINQ

LINQ over in-memory sequences and IQueryable sources: query syntax, deferred execution, operators and expression trees. Interviewers ask where a query really runs.

on this pageshow

explore

questions

24

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, how does query syntax such as from … where … select translate into method syntax, and which operators have no query keyword?

level: juniorimportance: must knowfreq 70%

basics

~20 s

Query syntax is a compile-time rewrite: the C# compiler turns each clause into a method call (where to Where, select to Select, join to Join), so both forms run identical code. Distinct, Take, Count, ToList and most other operators have no keyword.

open as a page

With LINQ to Objects, a Where query built before an order is added is then counted and looped over; what do Count() and foreach see?

level: middleimportance: must knowfreq 80%

basics

~20 s

Both see the added order. Where only stores the source and the predicate; Count() runs the filter over the list as it is at that moment, and foreach later runs it again from the start.

open as a page

In C#, what is the difference between calling Where on an IEnumerable<T> and on an IQueryable<T>, and where does each filter run?

level: middleimportance: must knowfreq 80%

basics

~20 s

Where on an IEnumerable<T> binds Enumerable.Where: the lambda becomes a Func delegate that filters each item in memory. Where on an IQueryable<T> binds Queryable.Where: the lambda becomes an expression tree that the source's query provider executes, often in another process.

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#, an IEnumerable<decimal> built with Where and Select over orders is checked with Any(), totalled with Sum() and looped; why does the pricing call repeat, and how do you fix it?

level: seniorimportance: must knowfreq 70%

basics

~10 s

Any(), Sum() and foreach each enumerate the deferred query separately, so the Where predicate and the pricing selector run again on every pass. Materialise once with ToList() or ToArray() and use the stored results.

open as a page

A C# repository method takes a Func<Order, bool> filter and calls Where on its IQueryable<Order> source; why does the whole source get pulled into memory, and what is the fix?

level: seniorimportance: must knowfreq 65%

basics

~20 s

Queryable.Where takes only Expression<Func<Order, bool>>, so a Func argument binds Enumerable.Where: the provider runs the unfiltered source and the delegate filters every item in memory. Take Expression<Func<Order, bool>> instead, so the filter joins the provider's tree.

open as a page

In C# LINQ, how do ToList(), ToArray() and ToHashSet() differ when materialising a query, and what does each result share with the source?

level: middleimportance: should knowfreq 50%

basics

~20 s

All three enumerate the query once and store the results: ToList() in a growable List<T>, ToArray() in a fixed-length array, ToHashSet() in a HashSet<T> without duplicates. Later source rows are absent, but changes to shared element objects show through.

open as a page

In C#, what does the compiler produce when the same lambda is assigned to a Func<Order, bool> and to an Expression<Func<Order, bool>>?

level: middleimportance: should knowfreq 58%

basics

~20 s

Assigned to Func<Order, bool>, the lambda compiles to a method you call through a delegate. Assigned to Expression<Func<Order, bool>>, the compiler emits code that builds a tree describing the lambda: data you inspect, translate or Compile() into a delegate.

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

When a C# LINQ query projects into new { l.Title, l.Author }, what type does the compiler create, and how do its instances compare?

level: middleimportance: should knowfreq 50%

basics

~20 s

The compiler generates an internal sealed class with read-only properties named after the projected members. It overrides Equals, GetHashCode and ToString using the property values, so Distinct, group keys and join keys work, but == still compares references.

open as a page

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%

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.

open as a page

In C# query syntax, how do join … on … equals and join … into translate, and how do you write a left outer join?

level: middleimportance: should knowfreq 45%

basics

~20 s

join … on a equals b compiles to Join; adding into compiles to GroupJoin. Only equality is allowed, the outer source's key goes left of equals, and a left outer join is join … into g followed by from x in g.DefaultIfEmpty().

open as a page

In a C# query expression, what do a second from and a let clause compile to, and how do earlier range variables stay in scope?

level: middleimportance: should knowfreq 30%

basics

~20 s

A second from compiles to SelectMany, and let compiles to a Select that wraps the current range variables and the new value in an anonymous object. These hidden objects, called transparent identifiers, keep earlier range variables reachable in later clauses.

open as a page

In C#, a LINQ Where lambda captures a local minTotal that is reassigned before the foreach; which value filters, and why does a bad row throw inside the foreach?

level: seniorimportance: should knowfreq 50%

basics

~20 s

The reassigned value filters: the lambda captures the variable minTotal and reads it whenever the predicate runs, which is during enumeration. For the same reason a FormatException from decimal.Parse in the lambda surfaces in the foreach, not at Where.

open as a page

With LINQ to Objects over a large order export, why does Where followed by First stop early while OrderByDescending followed by Take(1) reads every row?

level: seniorimportance: should knowfreq 45%

basics

~20 s

Where streams: it yields each match as it reads it, so First stops at the first one. OrderByDescending is deferred but nonstreaming: on its first MoveNext it copies the whole source into an array and sorts before yielding anything.

open as a page

In C#, what do AsEnumerable() and AsQueryable() change about a LINQ query, and where do you put AsEnumerable when a provider cannot translate one of your methods?

level: seniorimportance: should knowfreq 50%

basics

~20 s

Neither copies data or runs the query; each changes which operators bind next. Operators after AsEnumerable() run in memory, everything before stays in the provider's tree. Place it after the last step the provider can handle, just before the untranslatable call.

open as a page

In C#, how do you build an Expression<Func<Order, bool>> filter at run time with the Expression factory methods, and why does joining two lambdas' bodies fail at Compile()?

level: seniorimportance: should knowfreq 40%

basics

~20 s

Create one ParameterExpression, build nodes with Expression.Property, Constant, GreaterThan and AndAlso, then wrap them with Expression.Lambda<Func<Order, bool>>. Joining two compiler-made lambdas' bodies fails because each refers to its own parameter object, so one is unbound.

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

A C# query sorts books with orderby b.Author followed by a second orderby b.Year descending, and authors come out interleaved — why, and what is the fix?

level: seniorimportance: should knowfreq 35%

basics

~20 s

Each orderby clause compiles to its own OrderBy or OrderByDescending call, and every OrderBy starts a new primary sort, so the year sort replaces the author sort. Writing one clause, orderby b.Author, b.Year descending, compiles to OrderBy then ThenByDescending.

open as a page

In C#, should a team's service methods return a lazy IEnumerable<T> LINQ query, a materialised List<T>, or an IReadOnlyList<T>, and how would you set that rule?

level: principalimportance: should knowfreq 40%

basics

~20 s

Most teams make methods materialise query results and say so in the type, typically IReadOnlyList<T>, so callers get a snapshot they can count and enumerate twice. A lazy IEnumerable<T> is reserved for deliberate streaming and documented.

open as a page

Should a C# repository or service return IQueryable<T> to its callers, and what rule would you set for your team about where IQueryable may travel?

level: principalimportance: should knowfreq 50%

basics

~20 s

Returning IQueryable<T> lets callers compose filters and paging the provider runs, but hands them an unexecuted query whose cost, failures and lifetime the data layer no longer controls. Most teams keep it inside the data layer.

open as a page