Element Operators

Method

Description

SQL equivalents

First, FirstOrDefault

Returns the first element in the sequence, optionally satisfying a predicate

SELECT TOP 1…ORDER BY…

Last, LastOrDefault

Returns the last element in the sequence, optionally satisfying a predicate

SELECT TOP 1…ORDER BY…DESC

Single, SingleOrDefault

Equivalent to First/ FirstOrDefault, but throws an exception if there is more than one match

ElementAt, ElementAtOrDefault

Returns the element at the specified position

Exception thrown

DefaultIfEmpty

Returns null or default(TSource) if the sequence has no elements

OUTER JOIN

Methods ending in “OrDefault” return default(TSource) rather than throw an exception if the input sequence is empty, or if no elements match the supplied predicate.

default(TSource) = null for reference type elements, or “blank” (usually zero) for value type elements.

First, Last, Single

Argument

Type

Source sequence

IEnumerable<TSource>

Predicate (optional)

TSource => bool

The following example demonstrates First and Last:

	int[] numbers  = { 1, 2, 3, 4, 5 };
	int first      = numbers.First();                  // 1
	int last       = numbers.Last();                   // 5
	int firstEven  = numbers.First (n => n % 2 == 0);  // 2
	int lastEven   = numbers.Last  (n => n % 2 == 0);  // 4

The following demonstrates First versus FirstOrDefault:

	// Throws an exception:
	int firstBigError = numbers.First (n => n> 10);

	// Evaluates to 0:
	int firstBigNumber =numbers.FirstOrDefault(n => n > 10);

To avoid an exception, Single requires exactly one matching element;

Get LINQ Pocket Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.