LLINQ in C#
1 / 11
LESSON 01

What LINQ actually is

Before writing a single query, build a mental model of what LINQ does under the hood: one query syntax, many data sources, and a pipeline that goes from your code to expression trees to results.

Overview of LINQIEnumerable vs IQueryableDeferred executionQuery pipeline

One language, every data source .NET 10

Language-Integrated Query — LINQ — bakes query capability directly into C#, so filtering, sorting, grouping, and joining aren't string-based APIs you learn per technology. They're first-class language constructs, the same way class or foreach are.

Before LINQ, querying a SQL database, an XML document, and an in-memory list meant three unrelated APIs: SQL text, XPath/XQuery, and hand-written loops. LINQ replaces all three entry points with a single, strongly-typed, compiler-checked query shape. You write the same where / select pattern whether the data lives in a List<T>, a database table via a provider like EF Core, or an XML tree via LINQ to XML.

Key ideaA LINQ query is just a strongly typed expression that describes what you want, not how to get it. The execution engine — LINQ to Objects, a database provider, or another IQueryable provider — decides how.
Program.cs
int[] numbers = [4, 8, 15, 16, 23, 42];

var evens = from n in numbers
            where n % 2 == 0
            orderby n descending
            select n;

foreach (var n in evens)
    Console.WriteLine(n);
// 42, 16, 8, 4

The architecture: from your code to results

Click each stage to see what actually happens between from and the values you iterate over.

01
Query expression
02
Standard operators
03
Provider
04
Data source
05
Deferred execution

IEnumerable<T> vs IQueryable<T>

This is the single most important distinction in LINQ. IEnumerable<T> queries compile to delegates — plain method calls that run in your process, item by item (LINQ to Objects). IQueryable<T> queries compile to expression trees — data structures describing the query, which a provider (like EF Core's SQL Server provider) translates into another language, typically SQL, and executes remotely.

IEnumerable<T>IQueryable<T>
Compiles toDelegates (Func<T,...>)Expression trees
Runs whereIn-processWherever the provider sends it (DB, service)
Typical sourceList<T>, arrays, in-memory dataEF Core DbSet<T>, remote query APIs
Custom C# methods inside queryAllowedOnly if the provider can translate them
Common trapCalling .ToList() too early on an IQueryable pulls the entire table into memory before filtering, because everything after that point runs as LINQ to Objects instead of SQL. Filter first, materialize last.

Deferred execution, step by step

A query variable stores intent, not results. Nothing runs until you enumerate it — with foreach, .ToList(), .Count(), and similar. Press run to watch a query travel from expression to materialized list.

Deferred query
var q = posts.Where(p => p.BlogId == 1); // nothing runs yet

Because execution is deferred, the same query variable re-runs every time you enumerate it, picking up any changes to the underlying source in between. This is powerful but also a classic source of bugs — enumerate a query twice inside a loop and you may re-run an expensive database call twice.

TipForce immediate execution when you need a stable snapshot: .ToList(), .ToArray(), .ToDictionary(). This also avoids the "multiple enumeration" pitfall.

Where LINQ shows up across .NET

IN-MEMORY

LINQ to Objects

Queries over List<T>, arrays, and anything implementing IEnumerable<T>. Covered in depth in this course.

DATABASE

LINQ to Entities (EF Core)

IQueryable<T> translated into SQL by a database provider.

XML

LINQ to XML

Query and construct XDocument/XElement trees with the same operators.

PARALLEL

PLINQ

Add .AsParallel() to spread a LINQ to Objects query across cores.

Practice

  1. Write a query expression over an int[] that keeps only values greater than 10, then convert it to method syntax.
  2. Explain, in one sentence, why calling .Where() on a List<int> twice in a loop is cheap, but doing the same on an EF Core IQueryable<T> can be expensive.
  3. Name one scenario where you'd deliberately force immediate execution with .ToList() instead of leaving a query deferred.
LESSON 02

Writing your first queries: syntax basics

Every LINQ query has three moving parts — obtain the source, express the query, execute it. You'll write the same logic two ways: declarative query syntax and chained method syntax, and learn when each shines.

Introduction to LINQ queriesQuery expression basicsWrite LINQ queriesWriting queries walkthrough

The three-part shape of every query

Regardless of syntax, a LINQ operation always does the same three things.

01

Obtain the source

Any type implementing IEnumerable<T> or IQueryable<T>.

02

Create the query

Describe what you want with query or method syntax. Nothing executes yet.

03

Execute the query

Iterate with foreach, or call ToList/Count/First to trigger it.

Program.cs
List<int> scores = [97, 92, 81, 60, 88];

// 1. source: scores
// 2. query: filter >= 80
IEnumerable<int> highScores =
    from s in scores
    where s >= 80
    select s;

// 3. execution happens here, on iteration
foreach (int s in highScores)
    Console.WriteLine(s);

Query syntax vs method syntax semantically identical

The compiler translates every query expression into standard query operator calls. Query syntax reads like a sentence; method syntax chains extension methods with lambdas. Some operators — Count(), Max(), First() — have no query-syntax keyword and must be called as methods, even inside an otherwise query-syntax pipeline.

query.cs
var query =
    from word in words
    where word.Length > 4
    orderby word
    select word.ToUpper();
method.cs
var query = words
    .Where(word => word.Length > 4)
    .OrderBy(word => word)
    .Select(word => word.ToUpper());
mixed.cs
int count =
    (from word in words
     where word.Length > 4
     select word).Count();  // Count() has no query-syntax form
When to prefer whichQuery syntax reads cleanest for from/where/orderby/group/join combinations. Method syntax is required for aggregates and is usually more compact for short single-operator pipelines.

Anatomy of a query expression

  • from — introduces the range variable and the source: from n in numbers.
  • where — a boolean filter, can appear multiple times.
  • orderby — sorts, optionally with descending and multiple keys separated by commas.
  • select / group — the terminal clause; every query ends with exactly one of these.
  • let — introduces a computed variable mid-query, so you don't repeat an expression.
LetClause.cs
var report =
    from p in products
    let discounted = p.Price * 0.9m
    where discounted < 50
    orderby discounted
    select new { p.Name, discounted };

Guided walkthrough: from loop to LINQ

A short progression showing how a hand-written loop collapses into a query — the same exercise the official walkthrough builds toward.

Step1.cs
var result = new List<string>();
foreach (var student in students)
{
    if (student.Score >= 90)
        result.Add(student.Name);
}
result.Sort();
Step2.cs
var result = students
    .Where(s => s.Score >= 90)
    .Select(s => s.Name)
    .OrderBy(name => name)
    .ToList();
Step3.cs
var result =
    (from s in students
     where s.Score >= 90
     orderby s.Name
     select s.Name).ToList();

Practice

  1. Rewrite a Where + OrderByDescending + Select method-syntax chain as query syntax.
  2. Add a let clause to avoid computing the same expression twice inside a where and a select.
  3. Explain why .Count() can't appear as a query-syntax clause.
LESSON 03

The C# language features that make LINQ possible

LINQ isn't magic — it's a handful of C# language features working together: implicitly typed variables, anonymous types, lambda expressions, extension methods, and expression trees. Understanding each demystifies every query you write.

Type relationshipsvar and anonymous typesLambdas & extension methodsExpression trees (intro)

Type relationships across a query

The type flowing through from, transformed by select, and the type of the final query variable are all connected — and the compiler infers every one of them.

TypeFlow.cs
List<Product> products = GetProducts();       // source: IEnumerable<Product>

var names =
    from p in products                          // p : Product
    select p.Name;                               // projects to string

// names : IEnumerable<string> — inferred, not Product anymore

The moment select projects to a different shape, the element type of the whole query changes. This is why a query that starts over Product can end up as IEnumerable<string> or IEnumerable<{ Name, Total }> with no cast required anywhere.

var and anonymous types essential for projections

Query results are frequently shaped by an anonymous type — a compiler-generated class with no name, created with new { ... }. Because it has no name, you can only hold a reference to it with var.

Anonymous.cs
var summary =
    from o in orders
    select new { o.Id, o.CustomerName, Total = o.Lines.Sum(l => l.Price) };

foreach (var row in summary)
    Console.WriteLine($"{row.Id}: {row.CustomerName} = {row.Total:C}");
Scope limitAnonymous types can't cross method boundaries as a declared return type. If you need to return a shaped result from a method, use a record instead.

Lambda expressions the engine of method syntax

Every method-syntax operator takes a delegate — almost always written as a lambda. The compiler infers parameter types from context, so you rarely annotate them.

Lambdas.cs
// expression lambda
var adults = people.Where(p => p.Age >= 18);

// statement lambda body
var validated = people.Where(p =>
{
    var isAdult = p.Age >= 18;
    var hasEmail = !string.IsNullOrEmpty(p.Email);
    return isAdult && hasEmail;
});

A lambda passed to an IEnumerable<T> operator compiles to a normal delegate and executes as C# bytecode. The exact same lambda passed to an IQueryable<T> operator compiles to an expression tree instead — the provider inspects its structure and translates it, which is why not every C# construct is legal inside a provider-translated query.

Extension members make it all attachable C# 14

Every standard query operator — Where, Select, OrderBy — is an extension member on IEnumerable<T> or IQueryable<T>, defined in the static Enumerable and Queryable classes. That's the only reason list.Where(...) compiles even though List<T> never declares a Where method itself.

ExtensionMember.cs
public static class MyQueryExtensions
{
    extension<T>(IEnumerable<T> source)
    {
        public IEnumerable<T> WhereNotNull() =>
            source.Where(x => x is not null)!;
    }
}

// usage — reads like a built-in LINQ operator
var clean = items.WhereNotNull();
C# 14 extension membersThe newer extension(...) block syntax generalizes the old "static method with this" trick and also supports extension properties, which classic extension methods couldn't do. It's what lets you build your own LINQ-style operators that feel native — covered hands-on in Lesson 10.

Expression trees: the bridge to IQueryable

When a lambda is assigned to Expression<TDelegate> instead of Func<TDelegate>, the compiler emits a data structure describing the code, rather than compiled IL. That structure is what an IQueryable provider walks to build SQL.

ExprTree.cs
Expression<Func<Product, bool>> predicate = p => p.Price > 50;

// predicate.Body is a BinaryExpression: (p.Price > 50)
// predicate.Parameters[0] is a ParameterExpression: p
Console.WriteLine(predicate.Body);   // (p.Price > 50)
Why it mattersThis is the entire reason EF Core queries can become SQL: your lambda never runs as C#. It's inspected as data and rewritten. Deep-dived in the Reference & Roadmap lesson.

Practice

  1. Write a query that projects into an anonymous type with three properties, then explain why the result variable must be declared with var.
  2. Convert a statement lambda with an if block into an equivalent single expression lambda.
  3. Describe, in your own words, the difference between a Func<T,bool> parameter and an Expression<Func<T,bool>> parameter.
LESSON 04

The standard query operators, and filtering data

Every LINQ capability — filtering, projecting, sorting, grouping, joining — is implemented as one of roughly fifty standard query operators defined on IEnumerable<T>. This lesson maps that whole toolbox, then goes deep on the operator you'll use most: filtering.

Standard query operators overviewWhereOfTypeDeferred vs immediate categorization

The operator families at a glance

The standard query operators group into families by what they do to the sequence. Every remaining lesson in this course is one of these families, in depth.

FamilyRepresentative operatorsCovered in
FilteringWhere, OfTypeThis lesson
ProjectionSelect, SelectManyLesson 5
ConversionToList, Cast, AsEnumerableLesson 5
SortingOrderBy, ThenBy, ReverseLesson 6
PartitioningTake, Skip, ChunkLesson 6
QuantifiersAny, All, ContainsLesson 6
Set operationsDistinct, Union, Except, IntersectLesson 7
GroupingGroupByLesson 7
JoiningJoin, GroupJoinLesson 8
Deferred vs immediateMost operators (Where, Select, OrderBy, GroupBy) are deferred — they build up a query without running it. Operators that must inspect every element to answer — Count(), ToList(), Sum(), Max() — execute immediately.

Filtering with Where

Where is the workhorse: it takes a predicate — Func<T,bool> — and yields only the elements that satisfy it, lazily, one at a time.

Filter.cs
var inStock =
    from p in catalog
    where p.Quantity > 0 && p.Category == "Electronics"
    select p;

// equivalent method syntax with an indexed predicate overload
var everyOther = catalog.Where((p, index) => index % 2 == 0);

The indexed overload — Where((item, index) => ...) — is available in method syntax only; there's no query-syntax equivalent, because query syntax can't express a positional index cleanly.

Multiple where clauses vs one compound condition

Stacking where clauses is equivalent to &&-combining them, but keeps each condition independently readable — and, for IQueryable sources, the provider still merges them into a single SQL WHERE.

Stacked.cs
var results =
    from o in orders
    where o.Status == OrderStatus.Shipped
    where o.Total > 100m
    select o;
Single.cs
var results =
    from o in orders
    where o.Status == OrderStatus.Shipped && o.Total > 100m
    select o;

Type-filtering with OfType<T>

When a sequence holds mixed or non-generic types (e.g. a non-generic ArrayList, or a base type with several subclasses), OfType<T> filters to elements assignable to T and returns them already cast, unlike Where(x => x is T) which still leaves the base type.

OfType.cs
List<Shape> shapes = [new Circle(4), new Square(3), new Circle(2)];

IEnumerable<Circle> circles = shapes.OfType<Circle>();
double totalArea = circles.Sum(c => c.Area);
TipPrefer OfType<T>() over Where(x => x is T).Cast<T>() — it's a single, well-known operator and reads more clearly.

Practice

  1. Filter a list of Employee objects to those hired in the last year using both one compound where and two stacked where clauses.
  2. Use the indexed Where overload to keep only elements at even positions.
  3. Given a List<object> mixing int and string, extract only the strings with OfType<string>().
LESSON 05

Projection operations and converting data types

Projection reshapes each element; conversion operators move data between sequence types and force execution. Together they're how you go from raw source data to exactly the shape your caller needs.

SelectSelectManyToList / ToArray / ToDictionaryCast & AsEnumerable

Select: one-to-one projection

Select transforms every element into a new shape — a different type, a subset of properties, or a computed value — without changing the number of elements.

Select.cs
var labels =
    from p in products
    select $"{p.Name} — {p.Price:C}";

// method syntax with the indexed overload
var numbered = products.Select((p, i) => $"{i + 1}. {p.Name}");

SelectMany: flattening one-to-many

SelectMany projects each element to a sequence, then flattens all those sequences into one. It's the operator behind "for each order, for each line item" style queries — and behind the multiple from clauses you saw building a card deck in the language tutorials.

SelectMany.cs
var allLineItems =
    from order in orders
    from line in order.Lines          // second 'from' = SelectMany
    select new { order.Id, line.Sku, line.Qty };

// equivalent method syntax
var flat = orders.SelectMany(o => o.Lines,
    (o, line) => new { o.Id, line.Sku, line.Qty });
Select vs SelectManySelect gives you a sequence of sequences (IEnumerable<IEnumerable<Line>>). SelectMany flattens that into one sequence (IEnumerable<Line>). Reach for SelectMany the moment you need a single flat result across a one-to-many relationship.

Forcing execution: ToList, ToArray, ToDictionary

These are conversion operators that also happen to trigger immediate execution — the query runs completely, right there, and the result is materialized into a concrete collection.

MethodResultUse when
ToList()List<T>You need indexing, further mutation, or a stable snapshot.
ToArray()T[]Fixed size, marginally less overhead than List<T>.
ToDictionary()Dictionary<TKey,TValue>You need O(1) lookup by a key selector.
ToHashSet()HashSet<T>You need fast Contains checks and uniqueness.
Materialize.cs
Dictionary<int, Customer> byId =
    customers.ToDictionary(c => c.Id);

List<string> topNames =
    customers.Where(c => c.Tier == "Gold")
             .Select(c => c.Name)
             .ToList();

Cast<T> and AsEnumerable<T>

Cast<T> converts a non-generic sequence (like ArrayList) into IEnumerable<T> by casting every element — it throws if any element isn't compatible, unlike the filtering OfType<T> from Lesson 4. AsEnumerable<T>() statically types a sequence as IEnumerable<T>, which is a common trick to force the rest of a query to run as LINQ to Objects instead of being translated by an IQueryable provider.

CastVsOfType.cs
ArrayList legacy = GetLegacyList();          // non-generic
IEnumerable<string> strict = legacy.Cast<string>();   // throws on mismatch

// drop into LINQ to Objects for a provider-unfriendly expression
var result = dbContext.Products
    .AsEnumerable()                          // switch off SQL translation here
    .Where(p => LocalOnlyRule(p));            // arbitrary C# now allowed
CarefulAsEnumerable() silently pulls everything before that point into memory as an IQueryable-to-IEnumerable switch. Put it as late in the chain as possible.

Practice

  1. Given List<Blog> where each has List<Post>, use SelectMany to get a flat list of every post title across all blogs.
  2. Build a Dictionary<string, Customer> keyed by email using ToDictionary.
  3. Explain when you'd reach for Cast<T> instead of OfType<T>.
LESSON 06

Sorting, partitioning, and quantifier operations

Three closely related families: ordering a sequence, slicing it into pages or windows, and asking true/false questions about it — Any, All, and Contains.

orderby / OrderBy / ThenByTake / Skip / ChunkAny / All / Contains

Sorting: orderby, OrderBy, ThenBy

A single orderby clause can carry multiple comma-separated keys — the equivalent of OrderBy(...).ThenBy(...) in method syntax. Each key can independently be ascending or descending.

Sort.cs
var sorted =
    from e in employees
    orderby e.Department, e.LastName, e.Salary descending
    select e;
Sort.cs
var sorted = employees
    .OrderBy(e => e.Department)
    .ThenBy(e => e.LastName)
    .ThenByDescending(e => e.Salary);
Common mistakeChaining .OrderBy(a).OrderBy(b) instead of .OrderBy(a).ThenBy(b) re-sorts from scratch on b and discards the first sort — always use ThenBy for secondary keys.

Reverse() reverses element order without comparing anything; it's O(n), unrelated to sorting logic.

Partitioning: Take, Skip, Chunk

Partitioning splits a sequence without reordering it — the classic building block for pagination.

Paging.cs
int pageSize = 20, pageNumber = 3;

var page = catalog
    .OrderBy(p => p.Name)
    .Skip((pageNumber - 1) * pageSize)
    .Take(pageSize)
    .ToList();

// TakeWhile / SkipWhile stop at the first element that fails a condition
var leadingEvens = numbers.TakeWhile(n => n % 2 == 0);

// Chunk (added in .NET 6) splits into fixed-size batches
foreach (int[] batch in numbers.Chunk(100))
    ProcessBatch(batch);
TipAlways pair Skip/Take with a deterministic OrderBy — paging over an unordered sequence can return inconsistent or duplicate rows across pages.

Quantifiers: Any, All, Contains

Quantifiers answer a yes/no question about a sequence and execute immediately, short-circuiting as soon as the answer is known.

Any()
at least one match?
All()
every element matches?
Contains()
specific value present?
Quantifiers.cs
bool hasOverdue = invoices.Any(i => i.DueDate < DateTime.Today);
bool allPaid    = invoices.All(i => i.Status == InvoiceStatus.Paid);
bool knowsSku   = skus.Contains("SKU-1042");

// Any() with no predicate just checks "is the sequence non-empty"
if (results.Any()) { /* ... */ }
Performance noteAny() is almost always better than Count() > 0 — Any stops at the first match; Count must enumerate everything (unless the source has a fast Count property).

Practice

  1. Implement page 2 of a 25-item-per-page listing using Skip/Take over a sorted sequence.
  2. Use All() to verify every order in a batch has a positive total.
  3. Explain why orderby a, b descending is not the same as sorting by a descending, b descending.
LESSON 07

Set operations and grouping data

Set operators treat sequences like mathematical sets — union, intersect, difference, uniqueness. Grouping buckets elements by a key, the LINQ equivalent of SQL's GROUP BY.

DistinctUnion / Intersect / ExceptGroupBy

Set operations

All four compare elements using default equality (or a supplied IEqualityComparer<T>) and always return elements without duplicates.

OperatorMeaning
Distinct()Removes duplicate elements from one sequence.
Union(b)All elements from both sequences, deduplicated.
Intersect(b)Only elements present in both sequences.
Except(b)Elements in the first sequence but not in the second.
SetOps.cs
int[] thisWeek = [1, 2, 3, 4, 5];
int[] lastWeek = [3, 4, 5, 6, 7];

var newIds      = thisWeek.Except(lastWeek);      // 1, 2
var returningIds = thisWeek.Intersect(lastWeek);   // 3, 4, 5
var allSeen     = thisWeek.Union(lastWeek);        // 1..7, no duplicates
var uniqueTags  = tags.Distinct();
Custom equalityFor reference types, pass an IEqualityComparer<T> (or use DistinctBy(keySelector), added in .NET 6) so "equal" means "same business key," not "same reference."
DistinctBy.cs
var uniqueByEmail = customers.DistinctBy(c => c.Email);

Grouping with group ... by / GroupBy

Grouping produces a sequence of IGrouping<TKey, TElement> — each item is itself a mini-sequence of the elements that share a key, plus a .Key property.

Group.cs
var byCategory =
    from p in products
    group p by p.Category into g
    orderby g.Key
    select new { Category = g.Key, Count = g.Count(), Total = g.Sum(p => p.Price) };
Group.cs
var byCategory = products
    .GroupBy(p => p.Category)
    .OrderBy(g => g.Key)
    .Select(g => new { Category = g.Key, Count = g.Count(), Total = g.Sum(p => p.Price) });

The into g clause is a query continuation — it lets you keep querying (order, filter, project) against the grouped result within the same expression instead of writing a nested query.

Grouping by a computed or composite key

CompositeKey.cs
// group by a tuple key: (year, month)
var byMonth = orders.GroupBy(o => (o.PlacedOn.Year, o.PlacedOn.Month));

foreach (var g in byMonth)
    Console.WriteLine($"{g.Key.Year}-{g.Key.Month}: {g.Count()} orders");
Watch forGrouping over an IQueryable against a database can be expensive to translate; for complex aggregates, verify the generated SQL (EF Core logs it) rather than assuming it's efficient.

Practice

  1. Given two int[] arrays of customer IDs from two campaigns, compute customers who received both using Intersect.
  2. Group a list of LogEntry by Severity and project each group to { Severity, Count }.
  3. Use DistinctBy to get one representative order per customer.
LESSON 08

Join operations

Joins correlate elements from two sequences by matching keys — inner joins, group joins (the basis of "left outer join" in LINQ), and cross joins for combinatorial pairing.

Inner joinGroup joinLeft outer join patternCross join

Inner join with join / Join

An inner join emits one result row per matching pair of elements — rows with no match on either side are dropped, exactly like a SQL INNER JOIN.

InnerJoin.cs
var query =
    from o in orders
    join c in customers on o.CustomerId equals c.Id
    select new { OrderId = o.Id, c.Name };
InnerJoin.cs
var query = orders.Join(customers,
    o => o.CustomerId,
    c => c.Id,
    (o, c) => new { OrderId = o.Id, c.Name });
Syntax noteQuery-syntax joins always use equals, never == — it's a dedicated keyword only valid inside a join clause.

Group join → left outer join pattern

join ... into g (or method-syntax GroupJoin) keeps every element from the left sequence, attaching a collection of matches from the right — including an empty collection when there's no match. Following it with DefaultIfEmpty() gives you a true left-outer-join shape, one row per unmatched left element with nulls on the right.

LeftOuter.cs
var query =
    from c in customers
    join o in orders on c.Id equals o.CustomerId into custOrders
    from o in custOrders.DefaultIfEmpty()      // flatten, keep customers with 0 orders
    select new
    {
        c.Name,
        OrderId = o?.Id ?? -1   // o is null for customers with no orders
    };
Why this shapeinto custOrders alone gives you one row per customer, each holding a nested sequence of their orders — useful for a "customer with order count" report. Adding the second from ... DefaultIfEmpty() flattens it into one row per order (or one null row for customers with none), matching a relational left join.

Cross join: every combination

Two consecutive from clauses with no correlating key produce the Cartesian product — every element of the first paired with every element of the second. Useful for generating combinations, like the classic playing-card deck (suits × ranks).

CrossJoin.cs
string[] sizes  = ["S", "M", "L"];
string[] colors = ["Red", "Blue"];

var variants =
    from size in sizes
    from color in colors
    select $"{size}-{color}";
// S-Red, S-Blue, M-Red, M-Blue, L-Red, L-Blue

Choosing the right join

NeedUse
Only matching pairsjoin ... on ... equals ...
Every left row, grouped matchesjoin ... into g
Every left row, flattened, nulls for no matchjoin ... into g, then DefaultIfEmpty()
All combinations, no keytwo plain from clauses

Practice

  1. Inner-join Employee to Department on DepartmentId, projecting employee name and department name.
  2. Turn that into a left outer join so departments with zero employees still show up with a placeholder.
  3. Generate every combination of 3 sizes and 4 colors using a cross join.
LESSON 09

Practical LINQ: files, strings, and collections

The official how-to articles boil down to three everyday scenarios: querying the file system, treating strings as character sequences, and querying plain in-memory collections. This lesson works through all three with realistic snippets.

LINQ and file directoriesLINQ and stringsLINQ and collections

Querying files and directories

Directory.EnumerateFiles and friends return lazily-evaluated IEnumerable<string> sequences — a natural LINQ source for filtering by extension, size, or recency.

FileQuery.cs
string root = @"C:\reports";

var recentLargeLogs =
    from path in Directory.EnumerateFiles(root, "*.log", SearchOption.AllDirectories)
    let info = new FileInfo(path)
    where info.Length > 1_000_000 && info.LastWriteTime > DateTime.Today.AddDays(-7)
    orderby info.LastWriteTime descending
    select new { info.Name, SizeMb = info.Length / 1_000_000.0 };

foreach (var f in recentLargeLogs)
    Console.WriteLine($"{f.Name} — {f.SizeMb:F1} MB");
TipPrefer EnumerateFiles over GetFiles when combining with LINQ — it streams results lazily instead of building the whole array up front, which matters on large directory trees.

Treating strings as sequences of characters

string implements IEnumerable<char>, so every standard query operator works on it directly — useful for character-level filtering, frequency counts, and simple text analysis without regex.

StringQuery.cs
string text = "The quick brown fox jumps over the lazy dog";

int vowelCount = text.Count(c => "aeiouAEIOU".Contains(c));

var wordLengths =
    from word in text.Split(' ')
    group word by word.Length into g
    orderby g.Key
    select new { Length = g.Key, Words = g.ToList() };

bool isPangram = "abcdefghijklmnopqrstuvwxyz"
    .All(c => text.ToLower().Contains(c));
Why this worksBecause string is just IEnumerable<char>, everything from Lessons 4–7 — Where, GroupBy, All, Distinct — applies to text with zero extra API surface.

Querying in-memory collections

The everyday case: filtering, projecting, and aggregating List<T>, arrays, and dictionaries already loaded in memory.

CollectionQuery.cs
Dictionary<string, int> inventory = new()
{
    ["Widget"] = 42, ["Gadget"] = 0, ["Gizmo"] = 17
};

// KeyValuePair is the element type when querying a Dictionary
var outOfStock =
    from kv in inventory
    where kv.Value == 0
    select kv.Key;

var summary = new
{
    Total = inventory.Values.Sum(),
    LowStock = inventory.Count(kv => kv.Value is > 0 and < 20)
};
Pattern to knowkv.Value is > 0 and < 20 combines LINQ with a C# relational pattern inside the lambda — perfectly legal for LINQ to Objects, but not always translatable by an IQueryable provider.

Practice

  1. Find every .csv file under a folder modified in the last 24 hours, sorted by size descending.
  2. Given a paragraph of text, list the 5 most frequent words using GroupBy + OrderByDescending.
  3. Query a Dictionary<string,double> of account balances for all accounts with a negative balance.
LESSON 10

Extending LINQ and building dynamic queries

You've used the standard operators — now write your own, and learn how to build a query whose shape isn't known until run time, plus a hands-on tutorial applying everything to a real mini-project.

Custom query operatorsExtension membersDynamic queriesTutorial: faro shuffle

Writing your own standard-style operator

A custom LINQ operator is just an extension member over IEnumerable<T> that itself uses yield return for deferred, lazy behavior consistent with the built-ins.

CustomOperators.cs
public static class SequenceExtensions
{
    extension<T>(IEnumerable<T> source)
    {
        // deferred: work only happens once the caller enumerates
        public IEnumerable<T[]> SlidingWindow(int size)
        {
            var buffer = new Queue<T>(size);
            foreach (var item in source)
            {
                buffer.Enqueue(item);
                if (buffer.Count > size) buffer.Dequeue();
                if (buffer.Count == size) yield return buffer.ToArray();
            }
        }
    }
}

// usage — chains like a built-in operator
var movingAverages = prices
    .SlidingWindow(3)
    .Select(w => w.Average());
Deferred execution matters here tooBecause the body uses yield return, nothing inside SlidingWindow runs until the caller iterates — keeping it composable with .Select(), .Where(), and everything else, exactly like the built-in operators from Lessons 4–8.

Building dynamic queries at run time

Sometimes the filter/sort criteria aren't known at compile time — a search screen with optional fields is the classic case. Compose the query incrementally by reassigning an IQueryable<T> or IEnumerable<T> variable; because operators are deferred, nothing executes until the whole thing is finally enumerated.

DynamicQuery.cs
IQueryable<Product> query = dbContext.Products;

if (!string.IsNullOrEmpty(nameFilter))
    query = query.Where(p => p.Name.Contains(nameFilter));

if (minPrice is not null)
    query = query.Where(p => p.Price >= minPrice);

if (sortByPriceDesc)
    query = query.OrderByDescending(p => p.Price);

var results = query.Take(50).ToList();   // one round trip, fully composed
Why this is safeEvery reassignment just wraps the previous IQueryable in another expression node. EF Core sees the fully composed tree only when ToList() runs, and translates the whole thing into a single SQL statement.

For truly dynamic property names (e.g. "sort by whatever column the user clicked"), you either switch on a known set of strings to pick a strongly-typed key selector, or use expression-tree-building helpers (like the community System.Linq.Dynamic.Core package) to construct a lambda from a string at run time.

Guided tutorial: generating sequences with LINQ

A compact version of the official "faro shuffle" exercise — it drills iterator methods (yield return), custom LINQ-style extension methods, and the eager/lazy distinction, using a deck of cards.

Deck.cs
static IEnumerable<string> Suits()
{
    yield return "clubs"; yield return "diamonds";
    yield return "hearts"; yield return "spades";
}
static IEnumerable<string> Ranks()
{
    for (int i = 1; i <= 13; i++) yield return i.ToString();
}
Deck.cs
var deck = from s in Suits()
           from r in Ranks()
           select s + r;
var startingDeck = deck.ToArray();   // eager: snapshot the order
Deck.cs
public static class CardExtensions
{
    extension<T>(IEnumerable<T> first)
    {
        public IEnumerable<T> InterleaveWith(IEnumerable<T> second)
        {
            using var e1 = first.GetEnumerator();
            using var e2 = second.GetEnumerator();
            while (e1.MoveNext() && e2.MoveNext())
            {
                yield return e1.Current;
                yield return e2.Current;
            }
        }
    }
}

Assigning deck to a variable is lazy — it re-evaluates Suits()/Ranks() every enumeration. Calling .ToArray() is eager — it locks in one snapshot you can compare shuffle-by-shuffle without the source regenerating underneath you.

Practice

  1. Write a custom extension operator EveryNth(int n) that yields every n-th element, lazily.
  2. Compose a dynamic query with three optional filters and a single terminal .ToList().
  3. Explain why the faro-shuffle deck must be materialized with .ToArray() before comparing "before" and "after" shuffle order.
LESSON 11

Reference & roadmap

A compact reference for everything adjacent to core LINQ — related technologies, version history, expression tree internals, and where to go next — gathered here so nothing from the source documentation is left uncovered.

LINQ providersVersion historyExpression trees deep linkFurther reading

The LINQ provider family

RELATIONAL

LINQ to Entities (EF Core)

Translates IQueryable<T> expression trees into SQL. Complex provider — supports the widest slice of query syntax.

XML

LINQ to XML

XDocument/XElement expose IEnumerable<T>, so standard operators query and even construct XML trees.

PARALLEL

PLINQ

AsParallel() partitions LINQ to Objects work across cores; use for CPU-bound, embarrassingly parallel queries only.

CUSTOM

Your own IQueryable provider

Implementing IQueryProvider is significant effort — reserved for building a new query backend, not typical app code.

Provider complexity spectrumA minimal provider might handle one method call against a narrow web API. A complex provider like EF Core has an open type system and must map arbitrary user-defined types — which is why it took years to mature.

Expression trees, one level deeper reference

Introduced conceptually in Lesson 3, expression trees are the data-structure representation of code — a tree of Expression nodes (BinaryExpression, MethodCallExpression, ParameterExpression, etc.) that can be inspected, translated, or even compiled back into a delegate at run time with .Compile().

CompileExpr.cs
Expression<Func<int, int>> square = x => x * x;
Func<int, int> compiled = square.Compile();
Console.WriteLine(compiled(5));   // 25 — runs as normal IL now

Building expression trees by hand — with Expression.Parameter, Expression.Call, and similar factory methods — is how libraries assemble a query dynamically from metadata rather than a fixed lambda. This is the mechanism behind most "dynamic filter" packages referenced in Lesson 10.

C# / LINQ version history through .NET 10

VersionWhat it added for LINQ
C# 3.0LINQ itself: query expressions, lambda expressions, extension methods, anonymous types, var.
.NET 6Chunk, DistinctBy, ExceptBy, IntersectBy, UnionBy, MinBy/MaxBy, and easier top-level Index property patterns.
.NET 9CountBy, AggregateBy for keyed aggregation without a full GroupBy allocation.
C# 14 / .NET 10Extension members (extension blocks) generalize custom LINQ-style operators beyond classic "this" extension methods — used throughout Lesson 10.
Planned / evolvingCommunity dynamic-query libraries and source-generator-based LINQ providers continue to evolve outside the BCL; check current NuGet listings before depending on any specific one in production.

Further reading & related tools

A from-scratch reimplementation of the standard query operators, useful once you're comfortable with this course and want to see exactly how Where/Select are built internally with iterators.
The official LINQ get-started articles ship runnable Try.NET snippets — useful for experimenting beyond this course's static examples.
Once you're writing IQueryable-backed queries against a real database, EF Core's own docs cover translation limits, query tags, and logging generated SQL — a natural next course after this one.
For the formal grammar behind query expressions (exactly how from/where/select desugar to method calls), the C# language specification is the authoritative source.

Practice

  1. Compile an Expression<Func<T,bool>> and invoke the resulting delegate directly.
  2. List two operators added since .NET 6 that you'd reach for instead of a manual GroupBy + Select.
  3. Name one query pattern that's easy in LINQ to Objects but must be checked carefully when moved to an EF Core IQueryable.