2.5 — LINQ: Query vs Method Syntax, and the Standard Operators¶
← Roadmap · Section: 2. Collections, LINQ and Async Prev: 2.4 yield and iterators · Next: 2.6 Deferred execution
Markers: ⭐ 💻 · Confidence: 🔴 · Last reviewed: —
TL;DR¶
- LINQ is a set of extension methods on
IEnumerable<T>that filter, transform and combine sequences. - Two ways to write it. Method syntax (
.Where(x => ...)) is what almost everyone uses. Query syntax (from x in ... where ...) compiles down to exactly the same thing. - Operators split into two groups: those that return a new sequence (lazy) and those that return a single value (run immediately).
The concept¶
Before LINQ, filtering a list meant writing the loop yourself:
Five lines that say almost nothing about intent. LINQ replaces it with one that does:
The point is not brevity for its own sake. It is that you describe what you want, not how to loop. That makes the code read like the requirement, and it means the same expression can run in memory or be translated into SQL without you rewriting it — see 2.7.
LINQ stands for Language Integrated Query. Every operator is an extension method
(1.14) on IEnumerable<T>, and
almost all of them take a delegate (1.11) —
usually written as a lambda.
How it works¶
The two syntaxes¶
They are equivalent. The compiler rewrites query syntax into method calls before anything runs.
// Query syntax — looks like SQL
var result = from o in orders
where o.Total > 100
orderby o.CreatedAt descending
select o.CustomerName;
// Method syntax — identical after compilation
var result = orders
.Where(o => o.Total > 100)
.OrderByDescending(o => o.CreatedAt)
.Select(o => o.CustomerName);
Method syntax is the common choice and what you should default to. Query syntax only
wins in two cases — joins and multiple let variables — where it genuinely reads better:
// Query syntax is clearly nicer here
var result = from o in orders
join c in customers on o.CustomerId equals c.Id
let discount = o.Total * 0.1m
where discount > 5
select new { c.Name, o.Total, discount };
The method-syntax equivalent of that join is noticeably uglier. Mixing both in one codebase is fine.
The operators worth knowing¶
Filtering — narrows the sequence
orders.Where(o => o.Total > 100); // keep matching items
orders.OfType<PriorityOrder>(); // keep items of a given type
orders.Distinct(); // remove duplicates
orders.DistinctBy(o => o.CustomerId); // .NET 6+ — distinct by a key
orders.Take(10); // first 10
orders.Skip(20).Take(10); // paging: items 21-30
orders.TakeWhile(o => o.Total > 0); // take until the test fails
Projecting — changes the shape
orders.Select(o => o.CustomerName); // one output per input
orders.Select((o, i) => $"{i}: {o.Id}"); // with the index
orders.SelectMany(o => o.Lines); // FLATTEN a list of lists
SelectMany is worth pausing on, because people find it confusing. Select gives you a
sequence of lists; SelectMany glues them into one:
// orders has 3 orders, each with 4 lines
orders.Select(o => o.Lines); // IEnumerable<List<OrderLine>> — 3 items
orders.SelectMany(o => o.Lines); // IEnumerable<OrderLine> — 12 items
Ordering
orders.OrderBy(o => o.CreatedAt);
orders.OrderByDescending(o => o.Total);
orders.OrderBy(o => o.Status).ThenBy(o => o.Total); // ThenBy for the tiebreak
orders.Reverse();
⚠️ Use ThenBy for a second sort key, not a second OrderBy. Two OrderBy calls
throw the first sort away entirely — the second one re-sorts from scratch.
Aggregating — these return a single value and run immediately
orders.Count(); // how many
orders.Count(o => o.Total > 100); // how many match
orders.Sum(o => o.Total);
orders.Average(o => o.Total);
orders.Min(o => o.Total);
orders.MaxBy(o => o.Total); // .NET 6+ — the ORDER, not the total
orders.Any(); // is there at least one?
orders.Any(o => o.Total > 1000); // does anything match?
orders.All(o => o.Total > 0); // do they all match?
⚠️ Use Any() rather than Count() > 0. Any() stops at the first item it finds;
Count() walks the entire sequence just to throw the number away. Against a database that
is EXISTS versus COUNT(*).
Element access — covered properly in 2.9
orders.First(); orders.FirstOrDefault();
orders.Single(); orders.SingleOrDefault();
orders.ElementAt(3);
Set operations
listA.Union(listB); // everything, no duplicates
listA.Intersect(listB); // only items in both
listA.Except(listB); // in A but not in B
listA.Concat(listB); // everything, duplicates kept
listA.SequenceEqual(listB); // same items, same order?
Materialising — forces execution and gives you a real collection
orders.ToList();
orders.ToArray();
orders.ToDictionary(o => o.Id);
orders.ToHashSet();
orders.ToLookup(o => o.CustomerId); // like a dictionary, but many values per key
Lazy or immediate?¶
This split matters more than any individual operator:
| Returns a sequence — lazy | Returns one value or a collection — runs now |
|---|---|
Where, Select, SelectMany |
Count, Sum, Average, Min, Max |
OrderBy, ThenBy, Reverse |
First, Single, Last, ElementAt |
Take, Skip, Distinct |
Any, All, Contains |
Union, Intersect, Except, Concat |
ToList, ToArray, ToDictionary |
Nothing in the left column does any work until something from the right column asks for results. That is 2.6, and it is the source of most LINQ surprises.
Code¶
A realistic pipeline, and how to keep it readable:
public IReadOnlyList<CustomerSummary> BuildSummaries(
IEnumerable<Order> orders,
DateTime since)
{
return orders
.Where(o => o.CreatedAt >= since) // narrow FIRST — cheapest step
.Where(o => o.Status == OrderStatus.Complete)
.GroupBy(o => o.CustomerId) // one group per customer
.Select(g => new CustomerSummary
{
CustomerId = g.Key, // Key is what you grouped by
OrderCount = g.Count(), // g is the orders in this group
TotalSpent = g.Sum(o => o.Total),
LastOrder = g.Max(o => o.CreatedAt)
})
.OrderByDescending(s => s.TotalSpent) // sort LAST — fewest items by now
.Take(100)
.ToList(); // one pass, executed here
}
Two ordering rules that are worth stating in an interview:
- Filter before you project or sort. Every later step then has less to do. Sorting ten thousand items and then keeping five is wasted work.
ToList()exactly once, at the end. Calling it midway forces everything up to that point into memory and throws away the laziness.
Interview questions¶
Q: What is the difference between query syntax and method syntax?
Nothing, functionally. The compiler translates query syntax into method calls before
anything runs, so both produce identical code. Method syntax is more common because it
covers every operator — some, like Count and ToList, have no query-syntax equivalent —
and it chains naturally. Query syntax is genuinely nicer for joins and for cases where you
need intermediate variables with let. Most codebases use method syntax by default and
drop into query syntax for complex joins.
Q: What is the difference between Select and SelectMany?
Select transforms each item into exactly one output, so if each order has a list of lines,
Select(o => o.Lines) gives you a sequence of lists. SelectMany does the same
transformation but then flattens the results into a single sequence, so you get all the
lines together rather than grouped by order. Whenever your projection returns a collection
and you want the contents rather than the collections, SelectMany is the one.
Q: Why prefer Any() over Count() > 0?
Any() stops as soon as it finds one item, whereas Count() walks the entire sequence and
then compares. On an in-memory list that is a waste; against a database it is the difference
between an EXISTS query that can stop at the first row and a COUNT(*) that scans
everything. The same reasoning applies to Any(predicate) over Where(predicate).Count() > 0.
Q: Does the order of LINQ operators matter?
Yes, both for correctness and performance. Filtering early means every subsequent operator
handles fewer items, so Where before OrderBy is much cheaper than the reverse. Some
orderings also change the result — Skip then Take is paging, while Take then Skip
is not. And a second OrderBy discards the first sort entirely, which is why you need
ThenBy for a secondary key.
Traps ⚠️¶
- A second
OrderBydiscards the first sort. UseThenByfor secondary ordering. Count() > 0instead ofAny()walks the whole sequence for no reason.- Calling
ToList()in the middle of a chain forces everything into memory and kills laziness. Do it once, at the end. Selectwhen you meantSelectManyleaves you with a sequence of collections.Sumon an empty sequence returns 0, butAverage,MinandMaxthrow. Guard withAny()or use nullable versions.- LINQ over an
IQueryablehas different capabilities to LINQ over objects. Some C# methods have no SQL equivalent and will either throw or silently pull the whole table. See 13.10. OrderByhas to buffer everything to sort it, so it cannot stay fully lazy — it reads the entire source before producing the first item.
Related¶
- 2.4 yield and iterators — how LINQ operators are built
- 2.6 Deferred execution — when the work actually happens
- 2.7 Expression trees — how the same LINQ becomes SQL
- 2.8 Advanced operators —
GroupBy,Join,Aggregate - 2.9 First vs Single — the element operators in detail
- 1.11 Delegates — what every lambda here becomes