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); // 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.