Skip to content
Tutorials Center
My learning

Topics

Lesson 77 of 182 ยท Delegates, Events and LINQ

LINQ Basics

Learn LINQ in C# from scratch - Where, Select, OrderBy, First, Any, Count, ToList, anonymous projections and how an IEnumerable pipeline works, with runnable examples.

Most programs spend their time asking questions about collections: "which orders are unpaid?", "what are the names of all adults?", "who has the highest score?". Without help you answer each with a foreach loop, a temporary list and an if. LINQ (Language Integrated Query) gives you a small vocabulary of operations such as filter, transform, sort and aggregate, so the code says what you want instead of how to loop.

LINQ works on anything that implements IEnumerable<T>: arrays, List<T>, dictionaries, sets, strings (a sequence of char), and the results of other LINQ calls. The operators live in the System.Linq namespace, which is one of the implicit usings, so in our examples you can call them right away. This lesson covers the everyday operators and the mental model; the next lessons go deeper into grouping and joins, deferred execution and query syntax.

From a loop to a pipeline

Here is the same task twice: collect the squares of the even numbers, largest first.

C# Loop versus LINQ

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Read the LINQ version from top to bottom: take numbers, keep those that are even, turn each into its square, order descending, put the result in a list. Each step is an operator that takes a sequence in and gives a new sequence out, so you chain them into a pipeline. The arguments (n => n % 2 == 0) are lambda expressions that tell each operator what to do with each element.

The sample data

For the rest of the lesson we use a small list of products. record gives us a compact type with nice printing:

C#
record Product(string Name, string Category, decimal Price, int Stock);

Every example below is self-contained and includes this record and the list at the bottom or top.

Where: filtering

Where keeps the elements for which the predicate returns true:

C# Where

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Where never changes the original list. It produces a new sequence that yields only the matching items.

Select: transforming

Select applies a function to every element and returns the results. The output type can differ from the input type:

C# Select and anonymous types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

An anonymous type (new { ... }) is a class the compiler writes for you. You cannot name it, so you use var to hold it, but it has properties and value-based equality. It is perfect for the middle of a query. If the result must leave the method (return value, parameter), define a record or use a tuple instead: Select(p => (p.Name, p.Price)).

OrderBy, ThenBy and sorting

OrderBy sorts ascending by a key you choose; OrderByDescending goes the other way. ThenBy and ThenByDescending break ties:

C# Sorting

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The sort is stable: elements with equal keys keep their original relative order, so "pear" stays before "kiwi" in the first line. Do not call OrderBy twice to sort by two keys; the second call replaces the first ordering. Use ThenBy. Order() and OrderDescending() (.NET 7) sort by the element itself when you have no key.

First, Single, Last and their OrDefault versions

These pick one element. Choose by what you know should be true:

Method Returns If nothing matches If several match
First() the first element throws InvalidOperationException returns the first
FirstOrDefault() the first element default (null, 0, ...) returns the first
Single() the only element throws throws
SingleOrDefault() the only element default throws
Last() / LastOrDefault() the last element throws / default returns the last
C# Picking one element

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Single is a precondition check: "I expect exactly one". Use First when several are fine and you just want one, and the OrDefault forms when "none" is a normal outcome. For reference types, FirstOrDefault returns null, which the nullable type system will make you handle.

Any, All, Contains and Count

These answer yes/no or "how many" questions:

C# Any, All, Count, Sum and friends

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Prefer Any() to Count() > 0 when you only need to know whether there is something: Any stops at the first element, while Count may walk the whole sequence. For List<T> and arrays, Count() is smart and reads the stored length, but you cannot rely on that for every sequence. On a List<T>, use the Count property directly; on an array, Length.

All returns true for an empty sequence (nothing violates the rule), and Sum of an empty sequence is 0. But Max, Min and Average of an empty sequence of non-nullable values throw InvalidOperationException, so check with Any() or use DefaultIfEmpty.

Take, Skip, Distinct and friends

Slicing and de-duplicating:

C# Take, Skip, Distinct, Reverse

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Skip(n).Take(m) is the classic recipe for paging. Take also accepts a Range (as in Take(^2..)), added in .NET 6. TakeWhile and SkipWhile stop testing at the first element that changes the answer, so they are not the same as Where.

Converting results: ToList, ToArray, ToDictionary

A query produces an IEnumerable<T>, which is only a recipe. To get a concrete collection, convert it:

C# Materializing results

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

ToDictionary throws ArgumentException if two elements produce the same key. If duplicates are possible, use ToLookup or group the data first (see LINQ Operators in Depth).

How an IEnumerable pipeline works

When you write numbers.Where(...).Select(...), nothing runs yet. Where returns an object that remembers its source and predicate; Select wraps that object. The work happens only when something pulls values: a foreach, ToList(), Count(), First() and so on. Then each element flows through the whole chain one at a time. You can see the order with side effects:

C# Elements flow through the pipeline one at a time

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Notice the interleaving: "Where checks 1", "Where checks 2", "Select doubles 2", "Got 4", and only then the next element. No temporary list is created between the steps. This deferred execution has big consequences, including surprises and performance wins, which are the whole subject of Deferred Execution and LINQ Pitfalls.

LINQ on strings and dictionaries

Any IEnumerable<T> works, including some that surprise beginners:

C# LINQ over strings and dictionaries

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Passing a method group such as char.IsDigit instead of a lambda is shorter and fine when the signature fits.

Common mistakes and good habits

  • Forgetting that queries are lazy. If you store a query and the source changes before you enumerate it, the result changes too. Call ToList() when you want a snapshot.
  • Enumerating more than once. Each foreach over a query re-runs it. That can be slow or repeat side effects (see the next lessons).
  • First when you meant FirstOrDefault. An exception on empty input is correct only if empty input is truly a bug.
  • Putting side effects in lambdas (printing, modifying lists). Keep the lambdas pure; use foreach for actions.
  • Over-chaining. A ten-operator chain that nobody can read is worse than a loop. Break it into named variables.
  • Using LINQ where a loop is clearer or faster. In hot paths with millions of items, a plain loop avoids delegate calls and allocations. Measure first.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does numbers.Where(n => n > 2) return?

    Where returns an IEnumerable that does the filtering when you enumerate it. It never modifies the source and does not build a list until you call ToList or similar.
  2. 2. You expect exactly one element to match and want an exception if there are zero or several. Which operator?

    Single throws InvalidOperationException when no element or more than one element matches. First accepts several matches; FirstOrDefault also accepts none.
  3. 3. Why is items.Any() usually better than items.Count() > 0?

    Any only needs to know whether a first element exists. Count may have to walk the entire sequence, which matters for lazy or expensive sources.
  4. 4. What is printed by Console.WriteLine(string.Join(",", new[] { 4, 4, 2 }.Distinct().OrderBy(n => n)));?

    Distinct removes the duplicate 4, leaving 4 and 2, and OrderBy sorts them ascending, giving 2,4.
  5. 5. You call OrderBy(a => a.Last).OrderBy(a => a.First) hoping to sort by first name and then by last name. What is the right assessment?

    A second OrderBy replaces the primary key. Stability happens to keep the earlier order for ties, but the clear and intended form is OrderBy(first).ThenBy(last).

Summary

  • LINQ turns loops into readable pipelines of operators over any IEnumerable<T>; the operators are in System.Linq.
  • Where filters, Select transforms (use anonymous types or records for projections), OrderBy/ThenBy sort stably.
  • First, Single, Last and their OrDefault forms pick one element; choose by what "none" or "many" should mean.
  • Any, All, Count, Sum, Min, Max, MinBy, MaxBy answer questions about a sequence; Max/Min/Average throw on empty non-nullable sequences.
  • Take, Skip, Distinct, Reverse slice and de-duplicate; ToList, ToArray, ToDictionary, ToLookup and ToHashSet materialize results.
  • Queries are lazy: elements flow through the chain one at a time, and the work happens when you enumerate.

Next: LINQ Operators in Depth