Skip to content

LINQ basics

LINQ — querying collections

LINQ (Language Integrated Query) lets you filter, transform and aggregate collections with short, readable code. You need using System.Linq;.

int[] numbers = { 5, 12, 8, 3, 20, 7 };

var evens   = numbers.Where(n => n % 2 == 0);     // 12, 8, 20
var doubled = numbers.Select(n => n * 2);         // 10, 24, 16, 6, 40, 14
var total   = numbers.Sum();                      // 55
var biggest = numbers.Max();                      // 20
var sorted  = numbers.OrderBy(n => n).ToList();   // 3, 5, 7, 8, 12, 20

The most-used methods

Method What it does
Where filters by a condition
Select transforms each element
OrderBy / OrderByDescending sorts
Any / All checks whether some / all match
First / FirstOrDefault the first element
Sum, Min, Max, Average, Count aggregates

Deferred execution

Where and Select don't run immediately — the query executes when you iterate it or call ToList()/ToArray(). If the source changes in between, the result differs.

The most common mistakes

  • First() on an empty collection throws — use FirstOrDefault().
  • Re-running the same query repeatedly — keep the result with ToList().

Practice

Try solving "Sum of an array" and "Largest of three numbers" using Sum() and Max().