Programming languages · Intermediate · 20 min
Query collections in C# with LINQ
By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · .NET 10 LTS (SDK 10.0.404, runtime 10.0.15, C# 14) · mcr.microsoft.com/dotnet/sdk:10.0
You will answer real questions about a list of school fee payments with LINQ in a .NET 10 file-based app, from filtering and grouping to left joins and CountBy, and see exactly when a query runs and why the same code becomes SQL in EF Core.
On this page
LINQ (Language Integrated Query) is the set of methods in System.Linq that lets you filter, sort, group, join and total any collection in C# with short, typed expressions. You write what you want, such as "payments over 50,000, newest first", and the method chain does the looping. The same methods work on arrays, lists and dictionaries in memory, and, through EF Core, on database tables, where they turn into SQL.
In this tutorial you work on one small, realistic data set: the fee payments a school has received this year, paid by bank transfer, card and mobile money. Each step answers a question a school bursar would ask, such as "how much came in for Term 1?" and "who has not paid at all?". By the end you know the core operators, the newer ones added in .NET 9 and 10 (CountBy, AggregateBy, Index, LeftJoin), and the one idea that causes most LINQ bugs: a query does not run when you write it.
You use .NET 10, the current long-term support release, with C# 14. .NET 11 shipped in November 2026 as a standard-term release; the code should work on it unchanged, but it was checked on .NET 10. All code runs as a .NET 10 file-based app: a single .cs file that dotnet run app.cs builds and runs, with no project file. With Native AOT turned off (shown in the first step), nothing is downloaded from NuGet.
You work in a throwaway folder, ~/linq-fees-demo, and delete it at the end.
Step 1 · Create the fee payments data
Make the folder and write the data. school.cs holds two record types and a static class with the sample lists. It has no statements of its own, so you never run it directly:
mkdir -p ~/linq-fees-demo
cd ~/linq-fees-demo
cat > school.cs <<'CS'
public record Student(int Id, string Name, string Year);
public record Payment(int Id, int StudentId, decimal Amount, string Term, string Method, DateOnly PaidOn);
public static class School
{
public static List<Student> Students { get; } =
[
new(1, "Amina Bello", "Year 7"),
new(2, "Kofi Mensah", "Year 7"),
new(3, "Wanjiru Kamau", "Year 8"),
new(4, "Tunde Adeyemi", "Year 8"),
new(5, "Zanele Dlamini", "Year 9"),
new(6, "Chidi Okafor", "Year 9"),
];
public static List<Payment> Payments { get; } =
[
new(101, 1, 45000m, "Term 1", "Bank transfer", new(2026, 9, 10)),
new(102, 2, 45000m, "Term 1", "Mobile money", new(2026, 9, 8)),
new(103, 3, 50000m, "Term 1", "Card", new(2026, 9, 9)),
new(104, 4, 25000m, "Term 1", "Mobile money", new(2026, 9, 15)),
new(105, 4, 25000m, "Term 1", "Mobile money", new(2026, 10, 1)),
new(106, 5, 55000m, "Term 1", "Bank transfer", new(2026, 9, 7)),
new(107, 1, 45000m, "Term 2", "Mobile money", new(2026, 11, 3)),
new(108, 3, 20000m, "Term 2", "Card", new(2026, 11, 5)),
];
}
CSA few things to notice in the data, because later queries depend on them:
- Amounts are
decimal, written with anmsuffix. Usedecimalfor money in C#:doublecannot store values such as 0.10 exactly, and the rounding errors add up in totals. - Tunde (student 4) paid Term 1 in two instalments of 25,000 by mobile money, which is common where families pay fees from a phone wallet as money comes in.
- Chidi (student 6) has paid nothing yet.
- The first two payments have the same amount but are listed out of date order. That matters when you sort.
A file-based app is one file. C# also requires top-level statements (the code that runs) to come before any type declarations in a file. So for each step you write the statements in queries.cs, then join the two files into app.cs and run that. Start with a first query that counts the lists.
The first line, #:property PublishAot=false, is a file-based app directive: it sets an MSBuild property for this app, and directives must come before any code. File-based apps turn on Native AOT publishing by default, which makes the first dotnet run download a few hundred megabytes of compiler and runtime packs from NuGet that you do not need just to run the code. Turning it off keeps the build to what the SDK already has:
cd ~/linq-fees-demo
cat > queries.cs <<'CS'
#:property PublishAot=false
var students = School.Students;
var payments = School.Payments;
Console.WriteLine($"{students.Count} students, {payments.Count} payments");
CS
cat queries.cs school.cs > app.cs
dotnet run app.csThe first run takes a few seconds while the SDK builds a hidden project for app.cs and caches it. Later runs of an unchanged file start faster.
Check it worked
The terminal prints 6 students, 8 payments. ls shows app.cs, queries.cs and school.cs, and no bin, obj or .csproj. If you see error CS8803: Top-level statements must precede namespace and type declarations, you joined the files the wrong way round: queries.cs must come first in the cat command.
Step 2 · Filter, sort and shape results
Most LINQ work is three operations chained together: Where keeps the items that pass a test, OrderBy sorts them, and Select turns each item into the shape you want to show. Each takes a lambda, a small inline function such as p => p.Method == "Mobile money" that receives one item, here named p.
Replace queries.cs with a list of mobile money payments, oldest first, and then a Term 1 list sorted by amount:
cd ~/linq-fees-demo
cat > queries.cs <<'CS'
#:property PublishAot=false
var payments = School.Payments;
var mobileMoney = payments
.Where(p => p.Method == "Mobile money")
.OrderBy(p => p.PaidOn)
.Select(p => $"{p.PaidOn:yyyy-MM-dd} #{p.Id} {p.Amount}");
Console.WriteLine("Mobile money, oldest first:");
foreach (var line in mobileMoney)
{
Console.WriteLine($" {line}");
}
var term1 = payments
.Where(p => p.Term == "Term 1")
.OrderByDescending(p => p.Amount)
.ThenBy(p => p.PaidOn);
Console.WriteLine("Term 1, largest first, then by date:");
foreach (var p in term1)
{
Console.WriteLine($" #{p.Id} {p.Amount} {p.PaidOn:yyyy-MM-dd}");
}
var sameAsQuerySyntax =
from p in payments
where p.Method == "Mobile money"
orderby p.PaidOn
select $"{p.PaidOn:yyyy-MM-dd} #{p.Id} {p.Amount}";
Console.WriteLine($"Query syntax gives the same result: {sameAsQuerySyntax.SequenceEqual(mobileMoney)}");
CS
cat queries.cs school.cs > app.cs
dotnet run app.csWhat each part does:
OrderByDescendingsorts largest first.ThenBybreaks ties: payments 101 and 102 are both 45,000, soThenBy(p => p.PaidOn)puts 102 (8 September) before 101 (10 September). Do not write a secondOrderByfor this; it would re-sort the whole list and throw the first sort away.Selectcan return anything. Here it builds a string; it could also build a new record or an anonymous object.- The
from ... where ... orderby ... selectblock is query syntax. The compiler turns it into exactly the sameWhere,OrderByandSelectcalls, which is whySequenceEqualreportsTrue. Query syntax reads well for joins over several sources; most C# code you meet uses method syntax, and some operators (Count,Sum,CountBy) exist only as methods. This tutorial uses method syntax from here on.
Check it worked
The mobile money list has four lines in date order, starting 2026-09-08 #102 45000 and ending 2026-11-03 #107 45000. The Term 1 list starts with #106 55000, then #103 50000, then #102 before #101. The last line ends with True.
Step 3 · Total, test and pick single items
Some operators return one value instead of a sequence. Sum, Count, Any and First answer questions directly:
cd ~/linq-fees-demo
cat > queries.cs <<'CS'
#:property PublishAot=false
var payments = School.Payments;
decimal term1Total = payments
.Where(p => p.Term == "Term 1")
.Sum(p => p.Amount);
Console.WriteLine($"Term 1 collected: {term1Total}");
int term2Count = payments.Count(p => p.Term == "Term 2");
Console.WriteLine($"Term 2 payments so far: {term2Count}");
Console.WriteLine($"Anyone paid by card? {payments.Any(p => p.Method == "Card")}");
Console.WriteLine($"Any single payment over 100000? {payments.Any(p => p.Amount > 100000m)}");
Payment tundeFirst = payments.First(p => p.StudentId == 4);
Console.WriteLine($"Tunde's first payment: #{tundeFirst.Id}");
Payment? chidiFirst = payments.FirstOrDefault(p => p.StudentId == 6);
Console.WriteLine(chidiFirst is null ? "Chidi: no payment found" : $"Chidi: #{chidiFirst.Id}");
try
{
payments.First(p => p.StudentId == 6);
}
catch (InvalidOperationException ex)
{
Console.WriteLine($"First() with no match throws: {ex.Message}");
}
CS
cat queries.cs school.cs > app.cs
dotnet run app.csHow to choose between them:
Any(test)stops at the first match, so it is the cheap way to ask "is there at least one?". Prefer it toCount(test) > 0, which has to look at every item.First(test)returns the first match and throwsInvalidOperationExceptionwhen there is none. Use it when no match means a bug.FirstOrDefault(test)returnsnull(or0for numbers) when there is no match. Use it when "not found" is a normal answer, and check fornullbefore you use the result. With nullable warnings on, which is the default, the compiler reminds you: the type isPayment?, notPayment.Sumof an empty sequence is0, butMax,MinandAverageof an empty sequence throw. Filter first and check withAnyif the list might be empty.
Check it worked
The output shows Term 1 collected: 245000, Term 2 payments so far: 2, True for card, False for over 100,000, Tunde's first payment: #104 and Chidi: no payment found. The last line ends with the exception message Sequence contains no matching element.
Step 4 · Group and join payments to students
GroupBy collects items that share a key into groups. Each group has a Key and is itself a sequence you can count or total. Join pairs items from two lists whose keys match, like a SQL inner join. .NET 10 adds LeftJoin, which keeps items from the first list even when there is no match.
cd ~/linq-fees-demo
cat > queries.cs <<'CS'
#:property PublishAot=false
var students = School.Students;
var payments = School.Payments;
var byMethod = payments
.GroupBy(p => p.Method)
.Select(g => new { Method = g.Key, Count = g.Count(), Total = g.Sum(p => p.Amount) })
.OrderByDescending(x => x.Total);
Console.WriteLine("By payment method:");
foreach (var m in byMethod)
{
Console.WriteLine($" {m.Method,-14} {m.Count} payments {m.Total}");
}
var term1Payments = payments.Where(p => p.Term == "Term 1");
var paidByName = term1Payments
.Join(students, p => p.StudentId, s => s.Id, (p, s) => (s.Name, p.Amount))
.GroupBy(x => x.Name)
.Select(g => $"{g.Key,-15} {g.Sum(x => x.Amount)}");
Console.WriteLine("Term 1 with Join (inner):");
foreach (var line in paidByName)
{
Console.WriteLine($" {line}");
}
var everyone = students
.LeftJoin(term1Payments, s => s.Id, p => p.StudentId, (s, p) => (s.Name, Amount: p?.Amount ?? 0m))
.GroupBy(x => x.Name)
.Select(g => $"{g.Key,-15} {g.Sum(x => x.Amount)}");
Console.WriteLine("Term 1 with LeftJoin:");
foreach (var line in everyone)
{
Console.WriteLine($" {line}");
}
CS
cat queries.cs school.cs > app.cs
dotnet run app.csReading the code:
new { Method = g.Key, ... }creates an anonymous object: a throwaway type with named properties, handy inside one method.(s.Name, p.Amount)is a tuple; C# names its partsNameandAmountfrom the properties you used.{m.Method,-14}pads the text to 14 characters, left-aligned, so the columns line up.Jointakes the other list, a key from each side (p.StudentIdands.Id), and a function that combines a matched pair. Tunde's two instalments come out as two pairs, and theGroupByadds them to 50,000.LeftJoinpassesnullfor the payment when a student has none, so the result function usesp?.Amount ?? 0m: "the amount if there is a payment, otherwise 0". Before .NET 10 this neededGroupJoin,SelectManyandDefaultIfEmptytogether; you will still see that pattern in older code.
Check it worked
The method summary lists Mobile money first with 4 payments 140000, then Bank transfer with 100000 and Card with 70000. The inner join list has five names and no Chidi. The LeftJoin list has all six students, with Chidi Okafor 0 at the end: that is the list of who still owes Term 1 fees.
Step 5 · Use CountBy, AggregateBy and Index
GroupBy builds a full list for every group even when you only want a count or a total. .NET 9 added CountBy and AggregateBy, which keep one running value per key instead. It also added Index, which pairs each item with its position, so you no longer need a counter variable in your loop.
cd ~/linq-fees-demo
cat > queries.cs <<'CS'
#:property PublishAot=false
var students = School.Students;
var payments = School.Payments;
Console.WriteLine("Payments per method:");
foreach (var (method, count) in payments.CountBy(p => p.Method))
{
Console.WriteLine($" {method}: {count}");
}
var names = students.ToDictionary(s => s.Id, s => s.Name);
var paidPerStudent = payments.AggregateBy(p => p.StudentId, 0m, (total, p) => total + p.Amount);
Console.WriteLine("Paid so far this year:");
foreach (var (studentId, total) in paidPerStudent)
{
Console.WriteLine($" {names[studentId]}: {total}");
}
Console.WriteLine("Three largest payments:");
foreach (var (index, p) in payments.OrderByDescending(p => p.Amount).Take(3).Index())
{
Console.WriteLine($" {index + 1}. #{p.Id} {p.Amount}");
}
CS
cat queries.cs school.cs > app.cs
dotnet run app.csCountBy(key)returns key and count pairs, in practice in the order each key first appears (the docs do not promise an order). Each pair is aKeyValuePair, which you can split into two variables withvar (method, count).AggregateBy(key, seed, func)starts each key at the seed (0m) and appliesfuncfor every item with that key. Here it adds up amounts, so Amina's Term 1 and Term 2 payments make 90,000. The seed can be any type, such as a tuple holding a total and a count.Index()yields(Index, Item)pairs starting at 0, which is why the code printsindex + 1.Take(3)keeps the first three items. Three payments tie at 45,000;OrderByDescendingkeeps tied items in their original order (it is a stable sort), so #101 is third.
ToDictionary builds a lookup from student ID to name once, so each name lookup is instant instead of a search through the list. Students with no payments, such as Chidi, do not appear in paidPerStudent at all; use LeftJoin from the previous step when you need every student.
Check it worked
The output shows Bank transfer: 2, Mobile money: 4 and Card: 2; five students with totals, including Amina Bello: 90000; and a ranked list from 1. #106 55000 to 3. #101 45000.
Step 6 · Watch a query run later, and more than once
A LINQ query over a collection is a recipe, not a result. Writing payments.Where(...) stores the test; nothing is checked until something loops over the query with foreach, Count, ToList or similar. This is called deferred execution. It has two effects: the query sees changes made to the list after you wrote it, and it runs again every time you loop over it.
To watch it, this query counts how often its test runs:
cd ~/linq-fees-demo
cat > queries.cs <<'CS'
#:property PublishAot=false
var payments = new List<Payment>(School.Payments);
var checks = 0;
var bigPayments = payments.Where(p =>
{
checks++;
return p.Amount >= 50000m;
});
Console.WriteLine($"Checks after writing the query: {checks}");
Console.WriteLine($"Big payments: {bigPayments.Count()} (checks so far: {checks})");
payments.Add(new Payment(109, 6, 55000m, "Term 1", "Bank transfer", new DateOnly(2026, 11, 20)));
Console.WriteLine($"Big payments after Chidi pays: {bigPayments.Count()} (checks so far: {checks})");
checks = 0;
if (bigPayments.Any())
{
var total = bigPayments.Sum(p => p.Amount);
var count = bigPayments.Count();
Console.WriteLine($"{count} big payments, total {total}");
}
Console.WriteLine($"Checks when the query is reused three times: {checks}");
checks = 0;
var snapshot = bigPayments.ToList();
if (snapshot.Count > 0)
{
var total = snapshot.Sum(p => p.Amount);
Console.WriteLine($"{snapshot.Count} big payments, total {total}");
}
Console.WriteLine($"Checks with ToList first: {checks}");
CS
cat queries.cs school.cs > app.cs
dotnet run app.csThe counter tells the story:
- After writing the query, the test has run 0 times.
Count()runs it over all 8 payments. After Chidi's payment is added, the same query variable finds 3 big payments, because it reads the list again: 9 more checks, 17 in all.- The
ifblock uses the query three times (Any,Sum,Count), and each one starts from scratch: 3 checks forAny, which stops at the first match, plus 9 and 9. That is the multiple-enumeration trap. Over a list it only wastes time; over a query that reads a file, calls an API or hits a database, it repeats that work, and the results can differ between calls if the data changed in between. ToList()runs the query once (9 checks) and stores the results. Everything after that works on the stored list.
Rule of thumb: call ToList() or ToArray() when you will use a result more than once, or when you need a fixed snapshot. Keep a query deferred when you will use it once, or when you want it to see later changes. Many IDEs and analysers warn about "possible multiple enumeration" of an IEnumerable; take that warning seriously. Do not add or remove items from a list while a foreach over a query on it is running: .NET throws InvalidOperationException with "Collection was modified".
Side effects inside Where, like the counter here, are only for showing what happens. In real code keep lambdas free of side effects.
Check it worked
The output reads Checks after writing the query: 0, then Big payments: 2 (checks so far: 8), then Big payments after Chidi pays: 3 (checks so far: 17). The reuse line says 21 and the ToList line says 9, and both blocks print 3 big payments, total 160000.
Step 7 · See why the same query becomes SQL in EF Core
Every query so far worked on IEnumerable<T>: the lambdas are compiled into ordinary .NET code that runs item by item. LINQ has a second interface, IQueryable<T>. When you call Where on an IQueryable, the compiler stores the lambda as an expression tree, a data structure describing the code, instead of compiled code. A query provider can then read that tree and translate it into something else. EF Core's DbSet<T> is an IQueryable, and its provider translates the tree into SQL for your database.
You can see the tree without a database. AsQueryable() wraps a list in an in-memory IQueryable:
cd ~/linq-fees-demo
cat > queries.cs <<'CS'
#:property PublishAot=false
var payments = School.Payments;
IEnumerable<Payment> inMemory = payments.Where(p => p.Amount >= 50000m);
IQueryable<Payment> asQuery = payments.AsQueryable().Where(p => p.Amount >= 50000m);
Console.WriteLine($"IEnumerable result: {inMemory.Count()}");
Console.WriteLine($"IQueryable result: {asQuery.Count()}");
Console.WriteLine($"Expression tree: {asQuery.Expression}");
CS
cat queries.cs school.cs > app.cs
dotnet run app.csThe last line prints the query as data, something like ...Where(p => (p.Amount >= 50000)). The code is identical in both lines; only the type of the source changed. Against EF Core, that tree becomes a WHERE clause such as WHERE "Amount" >= 50000 (the exact SQL depends on the provider; SQLite, for example, compares decimals through a helper function), and only the matching rows come back over the network. With a Payment entity and a DbSet<Payment> Payments added to a DbContext like the one in Store data in an ASP.NET Core API with EF Core (that project has only books and loans as it stands), ToQueryString() shows you the SQL before it runs:
var big = db.Payments
.Where(p => p.Amount >= 50000m)
.OrderByDescending(p => p.PaidOn);
Console.WriteLine(big.ToQueryString()); // the SELECT ... WHERE ... ORDER BY statement
var rows = await big.ToListAsync(); // the query runs here, onceThree things follow from this:
- Deferred execution matters more. Each time you loop over a database query, EF Core sends it again. The
ToListrule from the previous step saves real round trips here. - Not everything can be translated. A call to your own C# method inside
Wherehas no SQL equivalent. EF Core throws an exception saying the expression could not be translated rather than guessing. Rewrite the condition with simple comparisons, or filter as much as possible in the database and finish in memory afterAsEnumerable(). - Where you switch matters.
db.Payments.AsEnumerable().Where(...)downloads every row and filters on your machine.db.Payments.Where(...).AsEnumerable()filters in the database. On a slow or metered connection, such as a server reached over prepaid mobile data, the difference is the whole table versus a few rows.
Check it worked
Both result lines say 2, and the expression tree line contains Where(p => (p.Amount >= 50000)). That printed text is what a provider such as EF Core receives instead of compiled code.
Step 8 · Clean up
Remove the demo folder:
rm -rf ~/linq-fees-demoThe SDK keeps the cached builds of file-based apps under your system's temporary folder, not in the demo folder, so deleting the folder leaves no build output behind in your home directory.
Check it worked
ls ~/linq-fees-demo reports No such file or directory.
Next steps
- Find null bugs at build time before they reach
FirstOrDefaultresults in production: Catch null bugs at compile time with C# nullable reference types. - Run these queries against a real database, and read the SQL EF Core sends: Store data in an ASP.NET Core API with EF Core.
- Compare LINQ with the Java equivalent, which has the same lazy evaluation and a few different choices: Transform collections with Java streams.
- Go back to the basics of the SDK and file-based apps: Hello World in C#.
Related tutorials
- Write safer PHP with strict types, enums and readonly classesYou will take a loosely typed PHP 8.5 order script that gets totals quietly wrong and turn it into a typed domain model with strict types, a backed enum, readonly value objects and match, then prove it with a clean PHPStan 2.3 run.
- Write reusable TypeScript with genericsYou will replace three copy-pasted lookup functions with one generic function, then build a type-safe pluck, a Result type, a hand-written mapped type and a tested fetchJson helper in TypeScript 7.
- Write regular expressions you can read and testYou will build a small, tested Python module that pulls dates, money amounts and Nigerian and Kenyan phone numbers out of messy SMS text, and know how to port its patterns to JavaScript and when to stop using a regex.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials