Element Operators
Method | Description | SQL equivalents |
|---|---|---|
| Returns the first element in the sequence, optionally satisfying a predicate | |
| Returns the last element in the sequence, optionally satisfying a predicate | |
| Equivalent to |
|
| Returns the element at the specified position | Exception thrown |
| Returns null or | |
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 | |
Predicate (optional) | |
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); // 4The 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;
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access