Module 1 · How LINQ Works · Lesson 1 of 14
LINQ in C#: What It Is and How a Query Runs
What this lesson teaches
LINQ in C# lets you filter, sort, and reshape data. Learn what a query describes, when it runs, and where its work happens.
LINQ stands for Language Integrated Query. It gives you a consistent C# way to query collections and other data sources, including databases through a provider.
By the end, you can explain:
- What LINQ adds to C#.
- Why declaring a query usually does not read its data yet.
- How
Where,Select, andTake(1)work together. - Whether a filter runs in your application or in a database.
What is LINQ in C#?
For collections, LINQ provides query methods in System.Linq that work over IEnumerable<T>.
An interface describes operations a type promises to support. IEnumerable<T> is the interface for a sequence: items that can be requested one after another. The T stands for the item type, such as int or an order class.
LINQ uses extension methods. An extension method is a static method in a static class. For LINQ to Objects, these methods live in the Enumerable class. You can call them as if they belonged to the collection, like orders.Where(...). The List<T> class itself does not contain a Where method.
A lambda is a small function written with =>. In order => order.Paid, the function takes an order and returns whether it is paid. A true-or-false function used for filtering is called a predicate.
The familiar methods describe different jobs:
| Method | What it asks for |
|---|---|
Where | Keep items that pass a condition. |
Select | Produce a result from each item. |
OrderByDescending | Put items in descending order. |
Take(1) | Return at most the first item. |
C# also offers query syntax, written with words such as from, where, and select. Method syntax uses calls such as .Where(...).
Query syntax is not inherently faster: the compiler translates it into the corresponding method calls. Microsoft's guide to writing LINQ queries explains this translation. Choose the form that makes your query easier to read. See query syntax versus method syntax.
The mistake to avoid. LINQ is not another name for SQL. It also queries ordinary C# collections without a database.
In an interview, say: “LINQ is Language Integrated Query. It provides query methods in System.Linq over IEnumerable<T>, plus C# query syntax. It gives collections and supported data providers a consistent querying style. Query syntax compiles to corresponding method calls, so it is not inherently faster.”
See when a shop query runs
A query has three parts: obtain the source, describe the query, and execute it. These are separate actions, as Microsoft's introduction to LINQ queries explains.
Enumeration means requesting the items in a sequence, usually with foreach. Deferred execution means that a query waits until enumeration to read its source and produce results.
Our shop has customers, products, and five orders. The data uses tuples, which group several named values into one item. Each order stores its city and total so we can focus on execution rather than combining lists.
The query selects paid orders, newest first, and produces rows containing only Id, City, and Total. Producing a new result shape is called a projection. Here, new { ... } creates an anonymous type, whose class name is supplied by the compiler.
The counter inside the filter is only there to reveal when filtering happens. The final part of the same program traces a smaller query.
Before running this .NET 10 console program, predict:
- The filter count after declaration, after
ToList, and afterCount. - Whether both syntax styles produce the same IDs.
- Which
WandSmessages appear before the first result.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
var culture = CultureInfo.InvariantCulture;
List<(int Id, string City)> customers = [(1, "Leeds"), (2, "York")];
List<(int Id, decimal Price)> products = [(1, 12.50m), (2, 30.00m)];
List<(int Id, string City, decimal Total, bool Paid, DateTime Placed)> orders =
[
(1, customers[0].City, products[0].Price, false, Date("2026-01-01")),
(2, customers[1].City, products[1].Price, true, Date("2026-01-02")),
(3, customers[0].City, products[1].Price, false, Date("2026-01-03")),
(4, customers[0].City, products[0].Price * 2, true, Date("2026-01-04")),
(5, customers[1].City, products[1].Price * 2, true, Date("2026-01-05"))
];
int filterCalls = 0;
var query = orders
.Where(order =>
{
filterCalls++;
return order.Paid;
})
.OrderByDescending(order => order.Placed)
.Select(order => new { order.Id, order.City, order.Total });
Console.WriteLine($"After declaration: {filterCalls}");
var rows = query.ToList();
Console.WriteLine($"After ToList: {filterCalls}");
foreach (var row in rows)
Console.WriteLine($"{row.Id} | {row.City} | {row.Total.ToString("F2", culture)}");
int paidCount = query.Count();
Console.WriteLine($"Paid orders: {paidCount}");
Console.WriteLine($"After Count: {filterCalls}");
var querySyntax =
from order in orders
where order.Paid
orderby order.Placed descending
select new { order.Id, order.City, order.Total };
string methodIds = string.Join(", ", rows.Select(row => row.Id.ToString(culture)));
string syntaxIds = string.Join(", ", querySyntax.Select(row => row.Id.ToString(culture)));
Console.WriteLine($"Method IDs: {methodIds}");
Console.WriteLine($"Query IDs: {syntaxIds}");
Console.WriteLine($"Same IDs: {StringComparer.Ordinal.Equals(methodIds, syntaxIds)}");
Console.WriteLine("Pull trace:");
var firstEven = new[] { 1, 2, 3 }
.Where(number =>
{
Console.WriteLine($"W{number}");
return number % 2 == 0;
})
.Select(number =>
{
Console.WriteLine($"S{number}");
return number * 10;
})
.Take(1);
foreach (int result in firstEven)
Console.WriteLine($"Result: {result}");
static DateTime Date(string text) =>
DateTime.ParseExact(text, "yyyy-MM-dd", CultureInfo.InvariantCulture);After declaration: 0 After ToList: 5 5 | York | 60.00 4 | Leeds | 25.00 2 | York | 30.00 Paid orders: 3 After Count: 10 Method IDs: 5, 4, 2 Query IDs: 5, 4, 2 Same IDs: True Pull trace: W1 W2 S2 Result: 20
After declaration, filterCalls is 0. The query describes work; it has not tested an order.
ToList() executes the query and stores the results in a new list. The filter examines all five orders, so the counter becomes 5. The stored rows have IDs 5, 4, 2, with totals 60.00, 25.00, 30.00.
query.Count() asks the original query for a count, not the stored list. It tests the five orders again, returns 3, and leaves the counter at 10.
To avoid the second pass, use rows.Count. It reads the stored list's count and does not run the filter again.
Both syntax styles produce IDs 5, 4, 2. Their different spelling does not change the requested filtering, ordering, or projection.
The mistake to avoid. query and rows are not interchangeable. One describes a query; the other holds results already retrieved by ToList.
In an interview, say: “Deferred execution means a query runs when enumerated, not when declared. If I loop over this query again, it runs again from the start. It reads the source as it is at that moment, so new or changed orders can appear. ToList executes and stores results immediately. Count and First also execute immediately to return their answers.”
How foreach pulls items through a query
Look at the program's final query, without the shop's sorting step.
foreach asks for a result. Take(1) asks the preceding Select for one item. Select needs an item from Where, and Where checks the source until something passes.
flowchart TD
F["foreach"] -->|"requests a result"| T["Take(1)"]
T -->|"requests one item"| S["Select"]
S -->|"requests a match"| W["Where"]
W -->|"reads until a match"| D["source: 1, 2, 3"]
Requests travel towards the source; matching data comes back through the chain.
The trace is W1, W2, S2, followed by Result: 20:
Wheretests 1 and rejects it.Selectnever sees 1.Wheretests 2 and accepts it.Selecttransforms 2 into 20.Take(1)has its one result, so no further source item is requested.
Where and Select are streaming: they can produce a result without first reading the entire source. This does not mean every input produces an output. A filter may reject many items before finding one match.
The mistake to avoid. This chain does not first filter the whole array and then transform everything left. It processes only enough input to satisfy the request.
In an interview, say: “In LINQ to Objects, foreach pulls results through the chain. Where reads until an item passes, Select transforms that item, and Take(1) stops after one result. Streaming operators do not need to read the entire source first.”
Deferred does not always mean streaming
The shop query is deferred, but its ordering step behaves differently from the small trace.
OrderByDescending must read all matching orders before it can identify the newest one. Such an operation is nonstreaming: it needs all its input before producing its first result. OrderBy and GroupBy are also deferred, nonstreaming operations.
Keep two questions separate:
- When does it start? Deferred operations wait for enumeration.
- How much must it read first? Streaming and nonstreaming operations differ here.
For the methods in this lesson, use this quick rule: a method returning another sequence (IEnumerable<T>) waits. A method returning a single answer (Count, First, Sum, Any) or a filled collection (ToList) runs now.
| Behaviour | Methods |
|---|---|
| Deferred, streaming | Where, Select, Take |
| Deferred, nonstreaming | OrderBy, OrderByDescending, GroupBy |
| Immediate, returning one answer | Count, First, Sum, Any |
| Immediate, storing results | ToList |
Immediate does not mean “reads every item.” Any, for example, can finish as soon as it finds a qualifying item.
A second enumeration can repeat work; see deferred execution and multiple enumeration costs.
Microsoft's introduction to LINQ queries explains these execution categories. The classification table lists which methods are immediate, deferred streaming, or deferred nonstreaming.
IEnumerable or IQueryable: where does the filter run?
LINQ to Objects means LINQ operating on objects in your application's memory. For our List<T>, the filtering lambda runs in the application itself.
A provider connects LINQ queries to another data source. IQueryable<T> keeps your query as data that the provider can read. The provider can turn it into something else, such as SQL.
On IEnumerable<T>, methods like Where take a Func<T, bool>: a delegate, which holds a function your program can call. On IQueryable<T>, Where takes an Expression<Func<T, bool>>, called an expression tree. This describes the lambda as data, so the provider can read it instead of calling it as ordinary application code.
Entity Framework Core, usually called EF Core, is a library for working with database data through C# objects. Its DbSet<T> represents a collection of database entities, which are objects mapped to database data. It supports IQueryable<T>.
For a translatable filter on an EF Core DbSet, the provider generates SQL and the database does the filtering. EF Core does not simply send arbitrary C# functions to the database.
AsEnumerable() switches subsequent LINQ operations to LINQ to Objects. It does not execute the database query at that line. Results are still requested later.
ToList() executes the query and stores the returned results. Subsequent LINQ operations on that list run in memory. Storing results takes extra memory, but lets you reuse them without rerunning the database query.
For translation details, see how EF Core runs a query.
You can see the switch without a database. This example uses AsQueryable() to represent an in-memory sequence as an IQueryable<int>. After AsEnumerable(), the next Where runs an ordinary lambda in the application.
using System;
using System.Collections.Generic;
using System.Linq;
IEnumerable<int> numbers = new[] { 1, 2, 3 };
var query = numbers.AsQueryable().Where(number => number > 1);
int filterCalls = 0;
var localQuery = query.AsEnumerable().Where(number =>
{
filterCalls++;
return number % 2 == 0;
});
Console.WriteLine($"Before foreach: {filterCalls}");
foreach (int number in localQuery)
Console.WriteLine($"Result: {number}");
Console.WriteLine($"After foreach: {filterCalls}");Before foreach: 0 Result: 2 After foreach: 2
The counter stays at 0 until foreach. The earlier filter supplies 2 and 3 to the local filter, so that filter runs twice and returns only 2. This example shows application-side execution, not database translation.
The mistake to avoid. Moving AsEnumerable before a filter does not make that filter SQL. It makes the filter run in your application on the results returned from the database.
In an interview, say: “LINQ to Objects uses IEnumerable and Func delegates to run filters in memory. IQueryable uses expression trees that a provider can read. With EF Core, a translatable filter becomes SQL, so the database filters the rows. AsEnumerable moves later filters into the application without executing immediately. ToList executes and stores results, using extra memory so I can reuse them.”
Keep actions out of query lambdas
A side effect is anything a lambda does besides returning its answer, such as changing a counter, saving data, or sending a message.
Our counter and trace messages deliberately use side effects to make execution visible. They are teaching tools, not a pattern for business actions.
For real work, use LINQ to choose the items. Then use an explicit foreach to save or send each one. Otherwise, declaring a query might do nothing, and enumerating it again might repeat an action.
The mistake to avoid. Do not put sending an email inside Select and assume it happens once. Query execution controls whether and when that lambda runs.
In an interview, say: “I keep query lambdas focused on filtering and producing results. I put saving or sending in an explicit foreach, because deferred execution and repeated enumeration make side effects inside a query hard to control.”
Check yourself
A deferred query filters five orders. You call query.ToList(), then query.Count(), without changing the source. What happens?
Show answer
Correct answer: D
ToList returns a separate collection. Calling Count on the original query requests that query again, rather than using the list.
An EF Core query calls AsEnumerable() before Where. Where does that subsequent Where filter run?
Show answer
Correct answer: A
AsEnumerable switches subsequent operators to LINQ to Objects. It does not immediately execute the query or translate the later filter into SQL.
Going deeper
An iterator provides sequence items as they are requested. You do not need to write one to use LINQ; execution mechanics and costs belong in custom LINQ operators, streaming, and buffering. Buffering means holding input or results in memory for later use.
With EF Core, an operation it cannot translate usually throws when the query runs; see query translation and client evaluation.
Practice
Use the LINQ to Objects execution and enumeration checklist when revising.
Then solve these coding problems:
Sources
- Extension methods - C# | Microsoft Learn: Static methods called as though they belonged to the extended type.
- IQueryable<T> Interface | Microsoft Learn: Queries represented for a provider to interpret.
- Expression Trees - C# | Microsoft Learn: Lambdas represented as data rather than executable delegates.
- Write LINQ queries in C# | Microsoft Learn: Query syntax and its translation into method calls.
- Introduction to LINQ Queries - C# | Microsoft Learn: LINQ's consistent query model, IEnumerable<T> and IQueryable<T>, query stages, deferred and immediate execution, storing results, and streaming versus nonstreaming operations.
- Client vs. Server Evaluation - EF Core | Microsoft Learn: Provider translation, AsEnumerable versus ToList, application-side processing, top-level projection evaluation, and exceptions for untranslatable expressions elsewhere.
Practice
Checked before publishing: C# examples run on .NET 10, links opened, reviewed while it was written and read in full. How lessons are checked
Updated 1 Dec 2026 ·