LINQ Basics
Querying and transforming collections declaratively with LINQ instead of hand-written loops.
2 min read
LINQ (Language Integrated Query) lets you filter, transform, and aggregate collections declaratively — you describe what you want, not the loop mechanics of how to get it.
The manual way
var numbers = new List<int> { 1, 2, 3, 4, 5, 6 };
var evens = new List<int>();
foreach (var n in numbers)
{
if (n % 2 == 0)
evens.Add(n);
}Six lines to say "the even numbers." LINQ says it directly.
Method syntax
using System.Linq;
var evens = numbers.Where(n => n % 2 == 0).ToList();Where filters using a lambda expression (n => n % 2 == 0 — an inline anonymous function meaning "given n, return whether it's even"). .ToList() at the end converts the lazy query result into a concrete List<int> — without it, Where just returns a deferred, unevaluated sequence.
Common LINQ methods you'll reach for constantly:
var doubled = numbers.Select(n => n * 2); // transform each element
var first = numbers.First(n => n > 3); // first match (throws if none)
var firstOrNone = numbers.FirstOrDefault(n => n > 100); // null/0 if none, no exception
var anyOdd = numbers.Any(n => n % 2 != 0); // true if any element matches
var total = numbers.Sum();
var max = numbers.Max();
var sorted = numbers.OrderBy(n => n).ToList();Chaining queries
LINQ methods compose, since each one returns a sequence the next can operate on:
var result = numbers
.Where(n => n % 2 == 0)
.Select(n => n * n)
.OrderByDescending(n => n)
.ToList();
// squares of even numbers, largest first: [36, 16, 4]Reading top to bottom, this is close to a plain-English description of the transformation — filter, then transform, then sort — which is exactly LINQ's appeal over an equivalent hand-rolled loop with intermediate variables.
Query syntax: the SQL-like alternative
LINQ also has a second syntax that reads more like SQL, compiling down to the same method calls:
var result = from n in numbers
where n % 2 == 0
orderby n descending
select n * n;Both syntaxes are equivalent — method syntax is far more common in real-world code because it composes more naturally and supports the full LINQ method set, while query syntax only covers a subset. Learn to read both, but default to writing method syntax.
Working with real objects, not just numbers, LINQ is just as natural:
var adultNames = users.Where(u => u.Age >= 18).Select(u => u.Name).ToList();That single line replaces a loop with an if, a List<string> to collect into, and an Add call — LINQ tends to compress the most common "transform this data" patterns dramatically.
Test what you just learned
4 quick questions. Get all of them right to unlock the next lesson.
You can take the quiz without an account — logging in just lets your result count toward your progress.