Roadmap › 1. .NET › Step 14
LQ
LINQ — Language Integrated Query
Query vs method syntax, deferred execution, filtering, projection, ordering, grouping, joins, aggregation, set and element operators, IEnumerable vs IQueryable, expression trees, performance and the classic LINQ interview programs.
What it is & where it is used
LINQ (Language Integrated Query) adds query capabilities directly to C#. One syntax works over many data sources:
| Provider | Data source | Runs |
|---|---|---|
| LINQ to Objects | IEnumerable<T> — arrays, lists, dictionaries | In memory |
| LINQ to Entities (EF Core) | IQueryable<T> → SQL | In the database |
| LINQ to XML | XDocument, XElement | In memory |
| PLINQ | .AsParallel() | Parallel, in memory |
| Others | Cosmos DB SDK, MongoDB driver, OData | Remote |
LINQ is built on C# 3.0 features: extension methods, lambda expressions, anonymous types, var, object initialisers and expression trees.
Versions & history
| Year | .NET / C# | LINQ additions |
|---|---|---|
| 2007 | .NET 3.5 / C# 3.0 | LINQ introduced: Where, Select, OrderBy, GroupBy, Join, ... ; LINQ to SQL, LINQ to XML |
| 2010 | .NET 4.0 | PLINQ (AsParallel), Zip |
| 2017–2019 | .NET Core 2.x–3.0 | Append, Prepend, SkipLast, TakeLast, ToHashSet |
| 2021 | .NET 6 | MinBy, MaxBy, DistinctBy, UnionBy, IntersectBy, ExceptBy, Chunk, Take(Range), TryGetNonEnumeratedCount |
| 2022 | .NET 7 | Order(), OrderDescending() |
| 2024 | .NET 9 | CountBy, AggregateBy, Index() |
| 2025 | .NET 10 | LeftJoin, RightJoin operators; System.Linq.AsyncEnumerable (async LINQ over IAsyncEnumerable<T>) in the box |
Lifecycle
How a LINQ query executes:
- Define — you compose operators (
Where,Select, ...). Nothing runs yet; you've built a query object (an iterator chain, or an expression tree forIQueryable). - Enumerate — execution starts when you iterate (
foreach) or call an immediate operator:ToList,ToArray,ToDictionary,Count,Sum,First,Any, ... - Pull pipeline (LINQ to Objects) — each element flows through
Where→Select→ consumer one at a time (streaming). Some operators must buffer everything first (OrderBy,GroupBy,Reverse,Distinctpartially). - Translation (IQueryable) — the provider (EF Core) walks the expression tree, translates it to SQL, sends it to the DB and materialises results.
- Re-enumeration re-runs the whole query — cache with
ToList()if you need the results more than once.
Tools used to develop
- LINQPad — the classic LINQ playground (C# queries against objects and databases, shows generated SQL).
- Visual Studio — IntelliSense, debugger "Results View" (careful: it enumerates the query).
- EF Core logging (
LogTo(Console.WriteLine),ToQueryString()) — see SQL generated from LINQ. - ReSharper/Rider — convert loops ↔ LINQ.
- SharpLab — see how query syntax lowers to method calls.
- BenchmarkDotNet — compare LINQ vs loops in hot paths.