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.
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.
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, 4The architecture: from your code to results
Click each stage to see what actually happens between from and the values you iterate over.
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 to | Delegates (Func<T,...>) | Expression trees |
| Runs where | In-process | Wherever the provider sends it (DB, service) |
| Typical source | List<T>, arrays, in-memory data | EF Core DbSet<T>, remote query APIs |
| Custom C# methods inside query | Allowed | Only if the provider can translate them |
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.
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.
Where LINQ shows up across .NET
LINQ to Objects
Queries over List<T>, arrays, and anything implementing IEnumerable<T>. Covered in depth in this course.
LINQ to Entities (EF Core)
IQueryable<T> translated into SQL by a database provider.
LINQ to XML
Query and construct XDocument/XElement trees with the same operators.
PLINQ
Add .AsParallel() to spread a LINQ to Objects query across cores.
Practice
- Write a query expression over an int[] that keeps only values greater than 10, then convert it to method syntax.
- 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.
- Name one scenario where you'd deliberately force immediate execution with .ToList() instead of leaving a query deferred.
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.
The three-part shape of every query
Regardless of syntax, a LINQ operation always does the same three things.
Obtain the source
Any type implementing IEnumerable<T> or IQueryable<T>.
Create the query
Describe what you want with query or method syntax. Nothing executes yet.
Execute the query
Iterate with foreach, or call ToList/Count/First to trigger it.
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.
var query =
from word in words
where word.Length > 4
orderby word
select word.ToUpper();var query = words
.Where(word => word.Length > 4)
.OrderBy(word => word)
.Select(word => word.ToUpper());int count =
(from word in words
where word.Length > 4
select word).Count(); // Count() has no query-syntax formAnatomy 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.
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.
var result = new List<string>();
foreach (var student in students)
{
if (student.Score >= 90)
result.Add(student.Name);
}
result.Sort();var result = students
.Where(s => s.Score >= 90)
.Select(s => s.Name)
.OrderBy(name => name)
.ToList();var result =
(from s in students
where s.Score >= 90
orderby s.Name
select s.Name).ToList();Practice
- Rewrite a Where + OrderByDescending + Select method-syntax chain as query syntax.
- Add a let clause to avoid computing the same expression twice inside a where and a select.
- Explain why .Count() can't appear as a query-syntax clause.
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 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.
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 anymoreThe 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.
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}");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.
// 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.
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();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.
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)
Practice
- Write a query that projects into an anonymous type with three properties, then explain why the result variable must be declared with var.
- Convert a statement lambda with an if block into an equivalent single expression lambda.
- Describe, in your own words, the difference between a Func<T,bool> parameter and an Expression<Func<T,bool>> parameter.
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.
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.
| Family | Representative operators | Covered in |
|---|---|---|
| Filtering | Where, OfType | This lesson |
| Projection | Select, SelectMany | Lesson 5 |
| Conversion | ToList, Cast, AsEnumerable | Lesson 5 |
| Sorting | OrderBy, ThenBy, Reverse | Lesson 6 |
| Partitioning | Take, Skip, Chunk | Lesson 6 |
| Quantifiers | Any, All, Contains | Lesson 6 |
| Set operations | Distinct, Union, Except, Intersect | Lesson 7 |
| Grouping | GroupBy | Lesson 7 |
| Joining | Join, GroupJoin | Lesson 8 |
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.
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.
var results =
from o in orders
where o.Status == OrderStatus.Shipped
where o.Total > 100m
select o;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.
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);
Practice
- Filter a list of Employee objects to those hired in the last year using both one compound where and two stacked where clauses.
- Use the indexed Where overload to keep only elements at even positions.
- Given a List<object> mixing int and string, extract only the strings with OfType<string>().
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.
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.
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.
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 });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.
| Method | Result | Use 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. |
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.
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 allowedPractice
- Given List<Blog> where each has List<Post>, use SelectMany to get a flat list of every post title across all blogs.
- Build a Dictionary<string, Customer> keyed by email using ToDictionary.
- Explain when you'd reach for Cast<T> instead of OfType<T>.
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.
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.
var sorted =
from e in employees
orderby e.Department, e.LastName, e.Salary descending
select e;var sorted = employees
.OrderBy(e => e.Department)
.ThenBy(e => e.LastName)
.ThenByDescending(e => e.Salary);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.
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);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.
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()) { /* ... */ }Practice
- Implement page 2 of a 25-item-per-page listing using Skip/Take over a sorted sequence.
- Use All() to verify every order in a batch has a positive total.
- Explain why orderby a, b descending is not the same as sorting by a descending, b descending.
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.
Set operations
All four compare elements using default equality (or a supplied IEqualityComparer<T>) and always return elements without duplicates.
| Operator | Meaning |
|---|---|
| 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. |
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();
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.
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) };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
// 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");Practice
- Given two int[] arrays of customer IDs from two campaigns, compute customers who received both using Intersect.
- Group a list of LogEntry by Severity and project each group to { Severity, Count }.
- Use DistinctBy to get one representative order per customer.
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 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.
var query =
from o in orders
join c in customers on o.CustomerId equals c.Id
select new { OrderId = o.Id, c.Name };var query = orders.Join(customers,
o => o.CustomerId,
c => c.Id,
(o, c) => new { OrderId = o.Id, c.Name });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.
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
};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).
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-BlueChoosing the right join
| Need | Use |
|---|---|
| Only matching pairs | join ... on ... equals ... |
| Every left row, grouped matches | join ... into g |
| Every left row, flattened, nulls for no match | join ... into g, then DefaultIfEmpty() |
| All combinations, no key | two plain from clauses |
Practice
- Inner-join Employee to Department on DepartmentId, projecting employee name and department name.
- Turn that into a left outer join so departments with zero employees still show up with a placeholder.
- Generate every combination of 3 sizes and 4 colors using a cross join.
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.
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.
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");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.
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));Querying in-memory collections
The everyday case: filtering, projecting, and aggregating List<T>, arrays, and dictionaries already loaded in memory.
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)
}; Practice
- Find every .csv file under a folder modified in the last 24 hours, sorted by size descending.
- Given a paragraph of text, list the 5 most frequent words using GroupBy + OrderByDescending.
- Query a Dictionary<string,double> of account balances for all accounts with a negative balance.
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.
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.
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());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.
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 composedFor 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.
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();
}var deck = from s in Suits()
from r in Ranks()
select s + r;
var startingDeck = deck.ToArray(); // eager: snapshot the orderpublic 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
- Write a custom extension operator EveryNth(int n) that yields every n-th element, lazily.
- Compose a dynamic query with three optional filters and a single terminal .ToList().
- Explain why the faro-shuffle deck must be materialized with .ToArray() before comparing "before" and "after" shuffle order.
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.
The LINQ provider family
LINQ to Entities (EF Core)
Translates IQueryable<T> expression trees into SQL. Complex provider — supports the widest slice of query syntax.
LINQ to XML
XDocument/XElement expose IEnumerable<T>, so standard operators query and even construct XML trees.
PLINQ
AsParallel() partitions LINQ to Objects work across cores; use for CPU-bound, embarrassingly parallel queries only.
Your own IQueryable provider
Implementing IQueryProvider is significant effort — reserved for building a new query backend, not typical app code.
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().
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
| Version | What it added for LINQ |
|---|---|
| C# 3.0 | LINQ itself: query expressions, lambda expressions, extension methods, anonymous types, var. |
| .NET 6 | Chunk, DistinctBy, ExceptBy, IntersectBy, UnionBy, MinBy/MaxBy, and easier top-level Index property patterns. |
| .NET 9 | CountBy, AggregateBy for keyed aggregation without a full GroupBy allocation. |
| C# 14 / .NET 10 | Extension members (extension blocks) generalize custom LINQ-style operators beyond classic "this" extension methods — used throughout Lesson 10. |
Further reading & related tools
Practice
- Compile an Expression<Func<T,bool>> and invoke the resulting delegate directly.
- List two operators added since .NET 6 that you'd reach for instead of a manual GroupBy + Select.
- Name one query pattern that's easy in LINQ to Objects but must be checked carefully when moved to an EF Core IQueryable.