LINQ: The SQL for Objects

LINQ: The SQL for Objects in C#: There are two ways to get five red items under fifty pounds out of a warehouse.

The Analogy: The Request Slip

There are two ways to get five red items under fifty pounds out of a warehouse. You can walk the aisles yourself with a clipboard, checking every shelf, writing down the ones that qualify, then sorting your notes at the end. Or you can hand a request slip to the warehouse: red, under fifty, cheapest first. What you get back is the answer. How the warehouse found it — which aisle it started in, whether it used the index — is not your problem.

LINQ is the request slip. Where, OrderBy, Select and their thirty-odd siblings describe what you want, and the loop that finds it is written once, inside the framework, correctly. The clipboard version of the query below is about twenty lines with two nested ifs and a manual sort; the slip is three.

The name is honest about the ancestry: this is SQL's declarative style, brought into the language and pointed at objects instead of tables.


Syntax or Core Structure

using System;
using System.Collections.Generic;
using System.Linq;                       // without this, none of the methods exist

record Product(string Name, string Category, decimal Price, int Stock);

class Program
{
    static void Main()
    {
        List<Product> products = new()
        {
            new("mug",    "kitchen",   7.50m, 40),
            new("kettle", "kitchen",  24.00m,  6),
            new("tee",    "clothing", 18.00m, 12),
            new("cap",    "clothing",  9.20m,  0),
            new("apron",  "kitchen",  15.50m,  3)
        };

        var cheapKitchen = products
            .Where(p => p.Category == "kitchen" && p.Price < 20m)   // filter
            .OrderBy(p => p.Price)                                  // sort
            .Select(p => $"{p.Name} {p.Price:F2}");                 // project

        Console.WriteLine(string.Join(", ", cheapKitchen));

        Console.WriteLine($"in stock: {products.Count(p => p.Stock > 0)} of {products.Count}");
        Console.WriteLine($"total value {products.Sum(p => p.Price * p.Stock):F2}");
        Console.WriteLine($"dearest: {products.OrderByDescending(p => p.Price).First().Name}");
        Console.WriteLine($"any free? {products.Any(p => p.Price == 0m)}");
        Console.WriteLine($"all named? {products.All(p => p.Name.Length > 0)}");

        foreach (var group in products.GroupBy(p => p.Category).OrderBy(g => g.Key))
            Console.WriteLine($"  {group.Key,-9} {group.Count()} items, avg {group.Average(p => p.Price):F2}");

        Product? missing = products.FirstOrDefault(p => p.Category == "garden");
        Console.WriteLine($"garden line: {missing?.Name ?? "none"}");
    }
}

Output:

mug 7.50, apron 15.50
in stock: 4 of 5
total value 706.50
dearest: kettle
any free? False
all named? True
  clothing  2 items, avg 13.60
  kitchen   3 items, avg 15.67
garden line: none

Every one of those lines is a loop you did not write. GroupBy in particular replaced last lesson's Dictionary<string, List<Product>> get-or-create idiom with four words — and each group is itself queryable, which is why group.Average(...) works inside the loop.


Technical Depth: Deferred Execution and the Operator Zoo

A query is a recipe, not a result

This is the single most important fact about LINQ, and the source of most surprises:

var names = new List<string> { "ada" };
IEnumerable<string> query = names.Select(n => n.ToUpper());   // nothing has run yet

names.Add("grace");                                          // the source changed...

Console.WriteLine(string.Join(",", query));                  // ADA,GRACE
Console.WriteLine(string.Join(",", query));                  // ADA,GRACE - and it ran twice

Select returned an object that knows how to produce the results. The work happens when something enumerates it — a foreach, a string.Join, a ToList. Two consequences: the query sees the source as it is at enumeration time, and enumerating twice does the work twice. If the source is a database or an expensive computation, call .ToList() once and pass the list around.

Streaming versus buffering

OperatorBehaviour
Where, Select, Take, Skip, SelectManyStream — yield each item as they go, constant memory
OrderBy, GroupBy, Reverse, JoinBuffer — must read the whole source before yielding anything
Count, Sum, Any, First, ToListExecute immediately and return a value

Order matters because of this: Where(...).OrderBy(...) sorts only the survivors, while OrderBy(...).Where(...) sorts everything and then throws most of it away. Filter first.

Any() versus Count() > 0 is the same idea. Any stops at the first match; Count walks the entire sequence.

The operators worth knowing by name

JobOperators
FilterWhere, OfType<T>
ProjectSelect, SelectMany (flatten)
SortOrderBy, OrderByDescending, ThenBy, Reverse
Group and joinGroupBy, Join, GroupJoin
AggregateCount, Sum, Min, Max, Average, Aggregate
TestAny, All, Contains
Pick oneFirst, Last, Single, ElementAt, and each one's ...OrDefault
Set logicDistinct, Union, Intersect, Except
SliceSkip, Take, SkipWhile, TakeWhile, Chunk
MaterialiseToList, ToArray, ToDictionary, ToHashSet, ToLookup
.NET 6 shortcutsMaxBy, MinBy, DistinctBy, CountBy, Zip

MaxBy deserves a note because the old way trips people up: products.Max(p => p.Price) gives you 24.00m, the price. products.MaxBy(p => p.Price) gives you the kettle.

First, Single, and the OrDefault twins

CallNo matchMore than one match
First(pred)throws InvalidOperationExceptionreturns the first
FirstOrDefault(pred)null / 0 / defaultreturns the first
Single(pred)throwsthrows
SingleOrDefault(pred)nullthrows

Use Single when "exactly one" is an invariant you want enforced loudly — looking up by primary key. Use First when you only want the front of a list. And note the trap for value types: FirstOrDefault on an IEnumerable<int> returns 0, which is indistinguishable from finding a real zero.

Flattening with SelectMany

string[][] teams = { new[] { "ada", "grace" }, new[] { "alan" } };
var flat = teams.SelectMany(t => t);                     // ada, grace, alan
var words = "one two three".Split(' ').SelectMany(w => w.ToCharArray()).Distinct();

Whenever Select hands you a sequence of sequences, SelectMany is the operator you actually wanted.

Query syntax says the same thing

var q = from p in products
        where p.Category == "kitchen"
        orderby p.Price
        select p.Name;

Identical to the method chain, compiled to the same calls. Method syntax wins for short chains; query syntax reads better when you need join, let or multiple from clauses. Mixing them in one project is normal.

IEnumerable versus IQueryable — the trap with a bill attached

db.Orders.Where(o => o.Total > 100m).Take(10);                 // becomes SQL: fast
db.Orders.ToList().Where(o => o.Total > 100m).Take(10);        // downloads EVERY order first

IQueryable<T> holds an expression tree that Entity Framework translates into SQL. The moment you call ToList, AsEnumerable or anything the provider cannot translate, execution moves into your process and the rest of the chain runs on data already fetched. Same LINQ, wildly different query plan.

Aggregate, when nothing else fits

int[] xs = { 3, 1, 4 };
int product = xs.Aggregate(1, (acc, x) => acc * x);           // 12
string csv = xs.Aggregate("", (acc, x) => acc + x + ",");     // "3,1,4," - prefer string.Join

Also worth knowing: Sum() over an empty sequence is 0, but Average(), Max() and Min() over an empty sequence throw. Guard with Any() or use the nullable overload.


Real World Example: The Weekly Sales Report

Reports are LINQ's home ground: group, aggregate, rank, format. The whole report below is one List<Sale> and five queries.

using System;
using System.Collections.Generic;
using System.Linq;

record Sale(string Rep, string Region, DateTime Date, decimal Amount);

class Program
{
    static void Main()
    {
        List<Sale> sales = new()
        {
            new("ada",   "north", new DateTime(2026, 3, 2), 1200m),
            new("grace", "south", new DateTime(2026, 3, 2),  450m),
            new("ada",   "north", new DateTime(2026, 3, 4),  800m),
            new("alan",  "west",  new DateTime(2026, 3, 4), 2100m),
            new("grace", "south", new DateTime(2026, 3, 5),  300m),
            new("ada",   "north", new DateTime(2026, 3, 6),  150m),
            new("alan",  "west",  new DateTime(2026, 3, 6),  975m)
        };

        decimal total = sales.Sum(s => s.Amount);

        var byRep = sales
            .GroupBy(s => s.Rep)
            .Select(g => new                      // an anonymous type: a throwaway shape
            {
                Rep = g.Key,
                Deals = g.Count(),
                Revenue = g.Sum(s => s.Amount),
                Best = g.Max(s => s.Amount)
            })
            .OrderByDescending(r => r.Revenue)
            .ToList();                            // materialise: we enumerate it below

        Console.WriteLine("rep     deals   revenue      best   share");
        foreach (var r in byRep)
            Console.WriteLine($"{r.Rep,-8}{r.Deals,5}{r.Revenue,10:F2}{r.Best,10:F2}{r.Revenue / total * 100m,7:F1}%");

        Console.WriteLine($"{"total",-8}{sales.Count,5}{total,10:F2}");

        var busiest = sales
            .GroupBy(s => s.Date)
            .OrderByDescending(g => g.Sum(s => s.Amount))
            .First();

        Console.WriteLine($"busiest day {busiest.Key:yyyy-MM-dd} with {busiest.Sum(s => s.Amount):F2} over {busiest.Count()} deals");

        var regions = sales.Select(s => s.Region).Distinct().OrderBy(r => r);
        Console.WriteLine($"regions: {string.Join(", ", regions)}");

        var bigDeals = sales
            .Where(s => s.Amount >= 1000m)
            .OrderBy(s => s.Date)
            .Select(s => $"{s.Rep} {s.Amount:F0}");

        Console.WriteLine($"deals over 1000: {string.Join(" | ", bigDeals)}");
    }
}

Output:

rep     deals   revenue      best   share
alan        2   3075.00   2100.00   51.5%
ada         3   2150.00   1200.00   36.0%
grace       2    750.00    450.00   12.6%
total       7   5975.00
busiest day 2026-03-04 with 2900.00 over 2 deals
regions: north, south, west
deals over 1000: ada 1200 | alan 2100

Read the leaderboard: ada closed the most deals but alan earned the most money, which is exactly the kind of thing a report exists to surface. Note the .ToList() on byRep — the sequence is enumerated once for the table, and without it the grouping and four aggregates would be recomputed on every pass. Deals is 2, 3 and 2 against a total of 7, which is the cheapest sanity check available: the parts must add up to the whole.


Common Mistakes

  1. Forgetting using System.Linq;. The error is "no method named 'Where'", which sounds like a missing package and is a missing line.
  2. Enumerating the same query twice. if (q.Any()) return q.First(); runs it twice; q.Count() in a loop condition runs it every iteration. ToList() once.
  3. Sorting before filtering. OrderBy(...).Where(...) sorts rows you are about to discard. Put Where first.
  4. Count() > 0 instead of Any(). On a lazy or infinite sequence, Count is the difference between instant and never.
  5. First() on a sequence that might be empty. InvalidOperationException: Sequence contains no elements. Use FirstOrDefault and check, or Any first.
  6. Max(x => x.Price) when you wanted the item. That returns the price. MaxBy returns the row.
  7. ToList() before the filter on a database query. You have just downloaded the table. Keep the chain on IQueryable until the last possible moment.
  8. Side effects inside a lambda — Select(x => { count++; return x; }). Deferred execution means you cannot predict how many times it runs, or whether it runs at all.

Best Practices

  • Filter early, project late: Where → OrderBy → Select. Each stage should hand the next one less work.
  • Materialise once with ToList() when a result is used more than once, and pass IReadOnlyList<T> onwards so nobody re-queries by accident.
  • Prefer the specific operator: Any over Count() > 0, MaxBy over OrderByDescending(...).First(), ToDictionary over a manual loop.
  • Name intermediate queries when a chain grows past three or four operators. var recent = ...; var byRep = recent.GroupBy(...) beats a twelve-line expression.
  • Use ThenBy for tie-breaks rather than sorting twice; OrderBy(x => x.Team).ThenBy(x => x.Name) is one sort with two keys.
  • Reach for query syntax when you need join or let, and method syntax everywhere else.
  • Guard aggregates against empty sequences: items.Any() ? items.Average(...) : 0, because Average on nothing throws.
  • Keep lambdas pure. A LINQ lambda should compute a value and touch nothing else; anything that mutates belongs in a foreach.

Practice Exercises

  1. Given int[] numbers = { 8, 3, 12, 7, 3, 20, 15, 4 }, use LINQ to print the even numbers in descending order, the count of values above 10, the average of the distinct values, and the two largest values as a comma-separated string.
  2. Take the Product list from the syntax section and produce a restock report: every product with Stock < 10, ordered by stock ascending then name, printed as "name (stock) - order N" where N brings it up to 10. Then print the total cost of that restock using Sum.
  3. Write two versions of the same question — "which category holds the most expensive product?" — one with GroupBy plus OrderByDescending, one with a single MaxBy. Print both answers and add a comment on which is clearer and which does less work.
  4. Build List<Sale> as in the report, then answer with LINQ: the rep whose average deal is largest (not the total), the regions that had no sale on 2026-03-04, and a per-day running list using GroupBy + OrderBy printed as "2026-03-02: 1650.00". Add a comment explaining why GroupBy had to buffer the whole sequence before it could yield the first group.