Skip to content
LINQ — Querying Collections
step 1/6

Reading — step 1 of 6

Learn

~3 min readCollections and LINQ

LINQ — Querying Collections

You already know the loop way: create an accumulator, iterate, test with if, update. LINQ (Language INtegrated Query) is C#'s declarative alternative — you describe what you want as a pipeline of operations, and the library does the iterating. Add using System.Linq; and every array and List grows a family of chainable methods:

using System.Linq;

int[] nums = { 3, 1, 4, 1, 5, 9, 2, 6 };

var evens   = nums.Where(n => n % 2 == 0);    // filter: 4, 2, 6
var squares = nums.Select(n => n * n);        // transform each: 9, 1, 16, ...
int sum     = nums.Sum();                     // 31
int max     = nums.Max();                     // 9
int count   = nums.Count(n => n > 4);         // 3
var sorted  = nums.OrderBy(n => n);           // ascending order
var unique  = nums.Distinct();                // duplicates dropped

The n => n % 2 == 0 syntax is a lambda — a tiny inline function: "given n, return whether n is even". Where keeps the elements for which the lambda returns true; Select replaces each element with the lambda's result (what other languages call map).

Pipelines: the power is in the chaining

Each LINQ method returns a sequence, so they snap together left to right:

int result = nums
    .Where(n => n % 2 == 0)     // keep the evens:   4, 2, 6
    .Select(n => n * n)         // square each:      16, 4, 36
    .Sum();                     // add them up:      56

Read it like a sentence: filter, transform, aggregate. The loop version of this is eight lines and a mutable accumulator; the pipeline is three steps that each do exactly one thing.

Two behaviors worth knowing early:

  • Laziness. Where and Select do not run when you write them — they run when something consumes the sequence (Sum(), ToList(), a foreach). A chain costs nothing until you actually pull results through it.
  • Empty-friendly aggregates. Sum() on an empty sequence returns 0 — safe. But Max(), Min(), and First() on an empty sequence throw InvalidOperationException. When "no match" is a legal outcome, reach for FirstOrDefault() or guard with Any().

The trap: pipeline steps in the wrong order

// Trap 1: square everything, forget the filter
int wrong = nums.Select(n => n * n).Sum();
// for 1 2 3 4 5: 1+4+9+16+25 = 55 — wanted only the evens' squares (20)

// Trap 2: sum the evens but forget to square them
int alsoWrong = nums.Where(n => n % 2 == 0).Sum();
// for 1 2 3 4 5: 2+4 = 6

A pipeline is only as correct as its steps and their order. Say the requirement out loud — "of the even numbers, the sum of their squares" — and translate it word by word: Where (keep evens), then Select (square), then Sum.

Your exercise

Read a line of space-separated integers — the starter parses them into nums. Using LINQ (Where, Select, Sum), print the sum of the squares of the even numbers only.

The grader's tests target both traps above: for 1 2 3 4 5 it expects 20 (square-everything gives 55; sum-evens-unsquared gives 6 — both fail), and for 1 3 5 it expects 0, which the correct pipeline produces for free because Sum() over an empty filtered sequence returns 0. Print only the number.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…