SP
← LINQ
JuniorLINQ

LINQ basics: filtering, sorting and picking elements

LINQ (Language Integrated Query) is a set of extension methods on IEnumerable<T> that let you describe what you want from a collection instead of writing the loop yourself. Each operator takes a sequence and returns either a new sequence or a single value.

Filtering and projecting

Where keeps elements for which a predicate is true; Select turns each element into something else. They run in the order you chain them.

int[] nums = [1, 2, 3, 4, 5, 6];
var tens = nums.Where(n => n % 2 == 0).Select(n => n * 10); // 20, 40, 60

Operators such as Where, Select and OrderBy return a sequence, so you can keep chaining. Count, First, Any, Sum return a single value and end the chain.

Sorting

OrderBy / OrderByDescending set the primary sort key. To break ties, add ThenBy / ThenByDescending; they only reorder elements whose earlier keys are equal.

var sorted = people.OrderBy(p => p.Age).ThenByDescending(p => p.Name);

Picking one element

Method No match More than one match
First throws InvalidOperationException returns the first
FirstOrDefault returns default(T) returns the first
Single throws throws
SingleOrDefault returns default(T) throws

default(T) is 0 for int, false for bool and null for reference types, so FirstOrDefault on a List<int> returns 0, never null. Use Single only when "more than one" really means corrupted data, because it has to keep reading to prove there is no second match.

Any, All, Count

  • Any(predicate) stops at the first match, so it is the right way to ask "is there at least one?". Count(...) > 0 reads everything.
  • All(predicate) returns true for an empty sequence: no element breaks the rule.
  • Contains(value) uses the type's equality. For a class without an overridden Equals, that is reference equality, so a new object with the same property values is not found. Records compare by value.

Aggregates on empty sequences

List<int> empty = [];
empty.Sum();      // 0
empty.Max();      // InvalidOperationException
empty.Average();  // InvalidOperationException
List<int?> maybe = [];
maybe.Max();      // null, no exception

Sum of nothing is 0. Min, Max and Average on an empty sequence of a non-nullable value type (int, decimal) throw, because there is no sensible answer. For reference types such as string, Min and Max return null instead. Check Any() first, use DefaultIfEmpty(), or project to a nullable type. Average of int values returns a double, so [1, 2] averages to 1.5; it is not integer division.

Materializing: ToList, ToArray, ToDictionary

ToList() and ToArray() run the query right away and copy the results into a new collection. The copy is a snapshot: adding to the source later does not change it.

ToDictionary(keySelector, valueSelector) throws ArgumentException when two elements produce the same key. It does not overwrite or skip duplicates. If keys can repeat, group the data instead (GroupBy, ToLookup) or choose one element per key first.

Query syntax vs method syntax

var q1 = from w in words where w.Length > 3 orderby w.Length select w.ToUpper();
var q2 = words.Where(w => w.Length > 3).OrderBy(w => w.Length).Select(w => w.ToUpper());

The compiler translates query syntax into the same method calls, so the two forms behave and perform identically. Some operators (Count, Distinct, Take) exist only as methods; mixing both styles is normal.

Distinct, Skip and Take

Distinct() removes duplicates using default equality. Strings compare case-sensitively, so "C#" and "c#" are different unless you pass a comparer such as StringComparer.OrdinalIgnoreCase.

Skip(n) skips the first n elements and Take(n) takes the next n. Together they implement paging:

var page = items.Skip((pageNumber - 1) * pageSize).Take(pageSize);

Neither throws when n is larger than the sequence: Skip(5) on three elements gives an empty sequence, and Take(5) gives the three elements that exist. LINQ operators never return null instead of a sequence.

Practise this level
20 questions
Practise →