SkillPilotAI

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

C#
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.

C#
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}");
Output
$ dotnet run Loop.csKabir: 5499Asha: 2499Ravi: 1299

30.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.
C#
var topPaid = orders    .Where(o => o.IsPaid && o.Amount > 1000)    .Select(o => $"{o.Customer}: {o.Amount}"); foreach (var line in topPaid)    Console.WriteLine(line);
Output
$ dotnet run Where.csAsha: 2499Kabir: 5499Ravi: 1299

30.5 OrderBy / OrderByDescending

  • OrderByDescending sorts biggest first; OrderBy sorts smallest first.
  • ThenBy / ThenByDescending break ties on a second key.
C#
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);
Output
$ dotnet run OrderBy.csKabir: 5499Asha: 2499Ravi: 1299
The LINQ pipeline
  1. 1.Source: orders list (5 orders)

  2. 2.Where: keep paid orders above 1000 (Asha, Kabir, Ravi 1299)

  3. 3.OrderByDescending: sort by Amount, biggest first

  4. 4.Select: shape each into "Customer: Amount"

  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

C#
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);
Output
$ dotnet run Query.csKabir: 5499Asha: 2499Ravi: 1299
PointMethod syntaxQuery syntax
Looks likeChained method calls with lambdasSQL: from, where, orderby, select
Compiled toMethod callsThe same method calls
First, Any, Single, CountAvailable directlyNo keyword, must mix with methods
Used in practiceMost common in daily codeSometimes for joins / readability

30.7 Picking one item: First, FirstOrDefault, Single

C#
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");
Output
$ dotnet run First.csAshanone
C#
var 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);
Output
$ 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.

C#
var ravi = orders    .Single(o => o.Customer == "Ravi");Console.WriteLine(ravi.Amount);
Output
$ dotnet run SingleDup.csUnhandled exception.System.InvalidOperationException:  Sequence contains more than one  matching element
Method0 matches1 match2+ matches
FirstInvalidOperationExceptionThat itemThe first one
FirstOrDefaultnull / defaultThat itemThe first one
SingleInvalidOperationExceptionThat itemInvalidOperationException
SingleOrDefaultnull / defaultThat itemInvalidOperationException
Which method to pick
  1. 1.Need just yes/no? Use Any (or All)

  2. 2.Need one item and a missing item is normal? FirstOrDefault + null check

  3. 3.Need one item and missing is a bug? First

  4. 4.Exactly one must exist and a duplicate is a bug (Id, email)? Single

  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.
C#
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 found

30.9 Rules

  1. Where to filter, Select to shape, OrderBy / OrderByDescending to sort.
  2. Any() to check existence, not Count() > 0.
  3. When missing is normal: FirstOrDefault with a null check.
  4. Single only when a duplicate is itself a bug.
  5. 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.