O'Reilly logo

LINQ Pocket Reference by Joseph Albahari, Ben Albahari

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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;

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required