LINQ basics
LINQ (Language Integrated Query) lets you say what you want from a collection (filter, shape, sort, pick one) instead of writing every step of a loop by hand. It works on any IEnumerable and never changes the original list.
30.1 Why is it used?
- A loop spells out how: empty list, foreach, if, Sort with a comparison, another loop to print.
- A small requirement change means re-reading and editing the whole loop, so mistakes creep in.
- With LINQ you write only what you want; the library handles how.
- The chain reads top to bottom like the question itself.
30.2 Sample data
List<Order> orders =[ new(1, "Asha", 2499m, true), new(2, "Ravi", 399m, true), new(3, "Meera", 1899m, false), new(4, "Kabir", 5499m, true), new(5, "Ravi", 1299m, true),]; record Order(int Id, string Customer, decimal Amount, bool IsPaid);30.3 The problem: a long loop recipe
Task: paid orders above 1000, biggest first.
var result = new List<Order>();foreach (var o in orders){ if (o.IsPaid && o.Amount > 1000) result.Add(o);}result.Sort((a, b) => b.Amount.CompareTo(a.Amount)); foreach (var o in result) Console.WriteLine( $"{o.Customer}: {o.Amount}");$ dotnet run Loop.csKabir: 5499Asha: 2499Ravi: 129930.4 Where + Select
- Where takes a lambda returning true/false; only true items move ahead.
- Select gives every remaining item a new shape (here a string).
- Without sorting, results stay in the original list order.
var topPaid = orders .Where(o => o.IsPaid && o.Amount > 1000) .Select(o => $"{o.Customer}: {o.Amount}"); foreach (var line in topPaid) Console.WriteLine(line);$ dotnet run Where.csAsha: 2499Kabir: 5499Ravi: 129930.5 OrderBy / OrderByDescending
- OrderByDescending sorts biggest first; OrderBy sorts smallest first.
- ThenBy / ThenByDescending break ties on a second key.
var topPaid = orders .Where(o => o.IsPaid && o.Amount > 1000) .OrderByDescending(o => o.Amount) .Select(o => $"{o.Customer}: {o.Amount}"); foreach (var line in topPaid) Console.WriteLine(line);$ dotnet run OrderBy.csKabir: 5499Asha: 2499Ravi: 1299- Step 1
1.Source: orders list (5 orders)
- Step 2
2.Where: keep paid orders above 1000 (Asha, Kabir, Ravi 1299)
- Step 3
3.OrderByDescending: sort by Amount, biggest first
- Step 4
4.Select: shape each into "Customer: Amount"
- Step 5
5.foreach: print the new result; orders itself is unchanged
LINQ always returns a new result; the original list never changes
30.6 Query syntax vs method syntax
var topPaid = from o in orders where o.IsPaid && o.Amount > 1000 orderby o.Amount descending select $"{o.Customer}: {o.Amount}"; foreach (var line in topPaid) Console.WriteLine(line);$ dotnet run Query.csKabir: 5499Asha: 2499Ravi: 1299| Point | Method syntax | Query syntax |
|---|---|---|
| Looks like | Chained method calls with lambdas | SQL: from, where, orderby, select |
| Compiled to | Method calls | The same method calls |
| First, Any, Single, Count | Available directly | No keyword, must mix with methods |
| Used in practice | Most common in daily code | Sometimes for joins / readability |
30.7 Picking one item: First, FirstOrDefault, Single
var big = orders.First(o => o.Amount > 2000);Console.WriteLine(big.Customer); var missing = orders .FirstOrDefault(o => o.Id == 99);Console.WriteLine(missing?.Customer ?? "none");$ dotnet run First.csAshanonevar kabir = orders .Single(o => o.Customer == "Kabir");Console.WriteLine(kabir.Amount); bool hasUnpaid = orders.Any(o => !o.IsPaid);Console.WriteLine(hasUnpaid); bool allPaid = orders.All(o => o.IsPaid);Console.WriteLine(allPaid);$ dotnet run Single.cs5499TrueFalse- Any: is there at least one match? Stops at the first match.
- All: does every item match?
Checkpoint: Ravi has two orders, so Single fails.
var ravi = orders .Single(o => o.Customer == "Ravi");Console.WriteLine(ravi.Amount);$ dotnet run SingleDup.csUnhandled exception.System.InvalidOperationException: Sequence contains more than one matching element| Method | 0 matches | 1 match | 2+ matches |
|---|---|---|---|
| First | InvalidOperationException | That item | The first one |
| FirstOrDefault | null / default | That item | The first one |
| Single | InvalidOperationException | That item | InvalidOperationException |
| SingleOrDefault | null / default | That item | InvalidOperationException |
- Step 1
1.Need just yes/no? Use Any (or All)
- Step 2
2.Need one item and a missing item is normal? FirstOrDefault + null check
- Step 3
3.Need one item and missing is a bug? First
- Step 4
4.Exactly one must exist and a duplicate is a bug (Id, email)? Single
- Step 5
5.Need many items? Where + OrderBy + Select
30.8 Common mistakes
- First when the item can be missing: orders.First(o => o.Id == 99) crashes with "Sequence contains no matching element".
- Fix: FirstOrDefault, then check for null and show a clear message (Order 99 not found).
- Single where duplicates are possible (Ravi).
- Count() > 0 instead of Any(); Any stops at the first match.
- Myth: LINQ is only for databases. It works on any IEnumerable (List, array, Dictionary, HashSet); with EF Core the same Where/Select becomes SQL.
var order = orders .FirstOrDefault(o => o.Id == 99);if (order is null) Console.WriteLine("Order 99 not found");else Console.WriteLine(order.Customer); // Order 99 not found30.9 Rules
- Where to filter, Select to shape, OrderBy / OrderByDescending to sort.
- Any() to check existence, not Count() > 0.
- When missing is normal: FirstOrDefault with a null check.
- Single only when a duplicate is itself a bug.
- Use method syntax day to day; LINQ never changes the original list.
30.10 Interview tips
- LINQ is C#'s built-in query feature that filters, shapes and sorts any IEnumerable with Where, Select, OrderBy.
- Query syntax and method syntax compile to the same method calls.
- First throws on no match; FirstOrDefault returns null/default.
- Single expects exactly one match and throws for zero or more than one.
- Any stops at the first match, so it beats Count() > 0.