Linq

By the end of this lesson you'll be able to query any collection in C# the way you'd ask a question in plain English — filtering, sorting, reshaping, and summarising data with short, readable chains instead of hand-written loops. This is the single most-used feature in everyday C#.

Learn Python, JavaScript, Java and more with free interactive lessons, real projects and AI-powered help. Beginner-friendly.

Part of the free C# course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

LINQ is like having a personal assistant for your data. Without it, finding the right records means opening a filing cabinet and flicking through every folder by hand (a for loop). With LINQ you just say: "give me all invoices over £500, newest first, and only the customer names." The assistant does the searching ( Where ), the sorting ( OrderBy ), and the tidying-up ( Select ) — and hands you exactly what you asked for, in one clean sentence. LINQ stands for Language Integrated Query : a query language baked right into C#.

Everything in LINQ works on IEnumerable T — the common interface every list, array, and most collections implement. That's why one set of operators works on all of them.

Running C# locally: install the .NET SDK or use dotnetfiddle.net . Remember using System.Linq; at the top of every file that queries.

1. Filtering & Transforming — Where and Select

The two workhorses of LINQ are Where and Select . Where filters : you give it a test (a lambda that returns true or false ) and it keeps only the items that pass. Select transforms : it runs a lambda on each item and gives you back the results — a process called projection . A lambda like n => n 5 is just a tiny inline function: read => as "goes to". Read this worked example, run it, then you'll write your own.

Your turn. The program below is almost complete — fill in the blank in the Where lambda so it keeps scores greater than 5, then run it and check the output.

2. Sorting & Projecting — OrderBy + Select

OrderBy sorts a sequence using the key its lambda returns — OrderBy(p => p.Price) sorts by price, smallest first; OrderByDescending reverses it. You'll almost always pair sorting with a Select projection to reshape each item into the form you want to show — a label, a summary, or a new object. Now you try: sort the prices, then project each into a tidy label.

3. Querying Collections of Objects

LINQ truly shines on lists of objects. You filter by a property ( s => s.GPA 3.6 ), sort by another, then project into exactly the shape you need. The single-item operators earn their keep here too: First grabs the first match (and throws if there isn't one), while Any and All answer yes/no questions about the whole sequence. Aggregates like Average(s => s.GPA) take a selector so they know which number to crunch.

4. Deferred vs Immediate Execution

This is the LINQ behaviour that surprises everyone once. A LINQ query is deferred (lazy): defining it doesn't run anything — it just stores the recipe . The work happens later, the moment you enumerate it (a foreach , string.Join , Count() , etc.). So if the source list changes between defining and running the query, the query sees the change. Calling ToList() (or ToArray() ) runs it immediately and snapshots the result, freezing it. Watch both happen.

These four operators all return one item, but they fail very differently — and choosing the wrong one is a classic source of crashes.

Rule of thumb: use FirstOrDefault when "no match" is normal and you'll check for null ; use First only when you're certain a match exists; reach for Single when a value must be unique (like a lookup by primary key) and you want it to blow up loudly if it isn't.

5. Query Syntax vs Method Syntax

C# gives you two ways to write the same query. Method syntax uses the extension methods and lambdas you've used so far ( .Where(...).OrderBy(...).Select(...) ) — it's the most common in production code and composes freely. Query syntax ( from ... where ... orderby ... select ) reads like SQL and can be clearer for joins and grouping. They compile to the same thing, so pick whichever is more readable. This example shows both, plus GroupBy to bucket items by a key.

Here's a small but real program that uses everything from this lesson at once — a Where filter with two conditions, an OrderByDescending sort, a Select projection into a formatted line, and a couple of one-line aggregates straight off the source list. You understand every part now.

Notice the report and the two summary lines each enumerate the list independently — that's deferred execution at work. For a handful of orders that's fine; for a huge or expensive source, call ToList() once and reuse the result.

Q: My query "re-ran" and gave different results — is that a bug?

No, that's deferred execution . A LINQ query is a recipe that runs each time you enumerate it, so it always reflects the source at that moment . If you want a fixed result, call .ToList() to run it once and snapshot it.

Q: When should I use First versus FirstOrDefault ?

Use FirstOrDefault when "no match" is a normal outcome — it returns null (or 0 for numbers) instead of throwing. Use First only when you're certain a match exists and an empty result genuinely is a bug.

Q: Is query syntax or method syntax "better"?

Neither — they compile to the same code. Method syntax is more common and composes more freely, so most teams default to it. Query syntax can read more clearly for joins and grouping. Pick whichever is easier to read for the query at hand.

Q: What is IEnumerable T and why do I keep seeing it?

It's the interface that means "a sequence you can iterate one item at a time." Lists, arrays, and most collections implement it, and LINQ operators both take and return it — which is exactly why the same Where / Select work on all of them, and why a chain stays lazy until you enumerate.

No blanks this time — just a brief and an outline to keep you on track. Starting from the list of products, chain Where + OrderBy + Select to build a list of premium products (over £50), cheapest first, formatted as "Name — £Price" , then print each line. Run it and check your output against the expected lines in the comments.

Practice quiz

What does the LINQ Where operator do?

  • Transforms each item into a new shape
  • Keeps only the items for which the test returns true
  • Sorts the sequence
  • Reduces the sequence to one value

Answer: Keeps only the items for which the test returns true. Where filters: it keeps only the items whose lambda returns true. Select is the one that transforms.

What does the Select operator do?

  • Filters out non-matching items
  • Groups items by a key
  • Transforms (projects) each item into something new
  • Counts the items

Answer: Transforms (projects) each item into something new. Select runs a lambda on each item and returns the results — a process called projection.

What does 'deferred execution' mean for a LINQ query?

  • The query runs once and caches forever
  • Defining the query runs nothing; the work happens when you enumerate it
  • The query runs on a background thread
  • The query is compiled to SQL

Answer: Defining the query runs nothing; the work happens when you enumerate it. A LINQ query is a recipe. Defining it runs nothing; the work happens the moment you enumerate it (foreach, Count(), etc.).

What does calling ToList() on a query do?

  • Keeps it deferred and lazy
  • Runs it immediately and snapshots the result
  • Sorts the result
  • Removes duplicates

Answer: Runs it immediately and snapshots the result. ToList() (or ToArray()) forces immediate execution and freezes the result into a concrete list, so later source changes don't affect it.

What happens when you call First() on an empty sequence?

  • It returns null
  • It returns 0
  • It throws InvalidOperationException
  • It returns an empty sequence

Answer: It throws InvalidOperationException. First() throws 'Sequence contains no elements' on an empty sequence. Use FirstOrDefault() when no match is a normal outcome.

How does FirstOrDefault() behave when there is no match?

  • Throws an exception
  • Returns the default value (null for reference types, 0 for numbers)
  • Returns the last item
  • Returns the whole sequence

Answer: Returns the default value (null for reference types, 0 for numbers). FirstOrDefault() never throws on an empty result; it returns the type's default (null or 0), which you then check for.

When does Single(predicate) throw?

  • Only when the sequence is empty
  • Never
  • When there are zero matches OR more than one match
  • Only when there are more than two matches

Answer: When there are zero matches OR more than one match. Single requires exactly one match; it throws if there are zero OR more than one. Use it when a value must be unique.

What does GroupBy return?

  • A single number
  • Groups, each with a Key and the items in that bucket
  • A sorted sequence
  • A boolean

Answer: Groups, each with a Key and the items in that bucket. GroupBy buckets items by a key; each group is an IGrouping with a .Key and is itself a sequence you can Count or Sum.

Which interface do LINQ operators both take and return, letting the same Where/Select work on lists and arrays?

  • IComparable<T>
  • IDisposable
  • IEnumerable<T>
  • ICollection

Answer: IEnumerable<T>. LINQ operators work on IEnumerable<T>, which lists, arrays, and most collections implement — that's why one operator set works on all of them.

Why might a query appear to 'change' after you define it?

  • It is a compiler bug
  • Because of deferred execution — it runs later and reflects the source at that moment
  • Because Where mutates the source
  • Because Select caches stale data

Answer: Because of deferred execution — it runs later and reflects the source at that moment. Deferred execution means the query runs each time you enumerate it, reflecting the source as it is then. Call ToList() to snapshot it.