Lesson 18 of 24

In progress

Course progress

C# and .NET

LINQ: querying in C#

Filter, project, group and order with LINQ, understand deferred execution, and know when a loop is clearer.

LINQ turns a query into a value you can pass around. The same operators work on lists, arrays, XML, databases and anything else implementing IEnumerable<T>.

What you will learn

  • Use Where, Select, OrderBy and GroupBy.
  • Understand deferred execution and multiple enumeration.
  • Choose between query syntax and method syntax.

A first query

record Product(string Name, decimal Price, bool InStock);
var products = new List<Product>
{
new("pen", 20m, true),
new("lamp", 1200m, false),
new("book", 450m, true)
};
var names = products
.Where(p => p.InStock)
.OrderBy(p => p.Price)
.Select(p => p.Name.ToUpperInvariant())
.ToList();
Console.WriteLine(string.Join(", ", names));   // PEN, BOOK

Each method returns a sequence, and ToList materialises it. Read top to bottom as a pipeline: keep in-stock products, sort by price, take the names, produce a list.

Select transforms, Where filters, OrderBy sorts. Those three cover most queries.

Deferred execution

var query = products.Where(p => p.InStock);
products.Add(new Product("desk", 900m, true));
Console.WriteLine(query.Count());   // includes the new product

A LINQ query is a description, not a result. It runs when enumerated, which means it sees changes made after the query was defined.

That is useful for composing queries and surprising when the source changes. ToList, ToArray, Count() and First() all force execution at that point.

The related trap is enumerating the same query twice, which runs the work twice:

var expensive = products.Where(p => p.Price > 100m);
if (expensive.Any())
{
Console.WriteLine(expensive.Count());   // second pass
}

Materialise once when you need more than one result from it.

Materialising at the right moment

A query stays a description until something enumerates it, which is useful right up to the point where it is not. Returning an IEnumerable<T> that reads a file means the caller may open the file long after the method returned, possibly after the file was deleted.

The rule is to materialise at the boundary where the data is known to be valid: ToList before returning from a method that reads a stream, and keep deferred execution inside a single method where the lifetime is obvious.

Grouping and aggregation

var byStock = products
.GroupBy(p => p.InStock)
.Select(g => new { InStock = g.Key, Count = g.Count(), Total = g.Sum(p => p.Price) });
foreach (var group in byStock)
{
Console.WriteLine($"{group.InStock}: {group.Count} products, {group.Total:F2}");
}

GroupBy produces groups with a Key and the matching elements. The anonymous type in Select names the result, which is what makes the output readable.

Sum, Average, Min, Max and Count work on any sequence; Aggregate is the general fold.

Joins

var orders = new[] { new { CustomerId = 1, Total = 500m }, new { CustomerId = 2, Total = 300m } };
var customers = new[] { new { Id = 1, Name = "Ana" }, new { Id = 2, Name = "Ravi" } };
var report = customers.Join(
orders,
c => c.Id,
o => o.CustomerId,
(c, o) => new { c.Name, o.Total });

Join is an inner join; GroupJoin plus SelectMany gives the left-join behaviour. For anything complex, a dictionary lookup is often clearer than a join expression.

Query syntax

var cheap = from p in products
where p.Price < 500m
orderby p.Price
select p.Name;

Query syntax compiles to the same method calls. It reads better for joins and let clauses; method syntax reads better for simple pipelines. Pick one per file and stay with it.

Null and empty

var first = products.FirstOrDefault(p => p.Price > 5000m);
Console.WriteLine(first?.Name ?? "none");
var total = products.Sum(p => p.Price);

First throws on an empty sequence; FirstOrDefault returns default, which is null for a reference type and 0 for int. For value types, prefer Where(...).Select(...).DefaultIfEmpty(...) or check Any() first, because 0 cannot be distinguished from a real zero.

Sum on an empty sequence returns 0 for numeric types, unlike SQL’s NULL, which is one of the few places C# and SQL disagree.

When a loop is better

LINQ is concise for transformations. It is worse when:

  • The body has several statements or early exits.
  • The query indexes parallel collections.
  • The work mutates state as it goes.
  • The reader has to trace types through four operators.

A foreach with a clear body is not a legacy style. Chaining six operators to save a loop often costs more in comprehension than it gains in brevity.

Performance notes

  • Count() on a List<T> is O(1); on a query it enumerates.
  • Where(...).Count() > 0 is slower than Any(), which stops at the first match.
  • OrderBy buffers the sequence; ToList after it is cheap because the data is already materialised.
  • Select before Where can do more work than necessary; filter first when the projection is expensive.

Returning a deferred query from a method that closes over a using block, so the sequence is enumerated after the resource is disposed. Materialise with ToList before returning.

Given a list of products, produce the three most expensive in-stock products as a list of names and prices, cheapest first.

Show solution
var top = products .Where(p => p.InStock) .OrderByDescending(p => p.Price) .Take(3) .OrderBy(p => p.Price) .Select(p => $"{p.Name} {p.Price:F2}") .ToList(); Console.WriteLine(string.Join("; ", top));

OrderByDescending with Take selects the three most expensive, and the second OrderBy puts them back in ascending order for display. Both sorts are stable, and ToList materialises the result so the query runs once.

Recap

  • Where, Select, OrderBy and GroupBy cover most queries; ToList materialises.
  • Queries are deferred, so they see later changes and re-run on each enumeration.
  • Filter before projecting, use Any() instead of Count() > 0, and prefer a loop when the body is complex.

Next, exceptions: catching what you can handle and letting the rest propagate.

Does LINQ work with a database?
With an `IQueryable` provider such as EF Core, the query is translated to SQL. The same operators, different execution.
Is query syntax better?
For joins and `let`, often. For a simple pipeline, method syntax is shorter.

Progress is saved in this browser only. No account, no email.

Admin

About the author

Admin

Instructor and technical writer at tutorials.in

Writes beginner lessons for tutorials.in. Each lesson is checked against the language or tool documentation, and examples are run before publishing.

Reviewed by the editorial team before publishing. Last updated November 16, 2026.