Java Reference
In-Depth Information
Table 3-1.
(
continued
)
Operation
Description
firstOrDefault
Iterates over the source elements, and if a predicate function is specified, then the first
element returning a
true
result is yielded. Otherwise, if no predicate function is specified,
the
firstOrDefault
operator simply returns the first element in the collection.
If no element matches the predicate or if the source sequence is empty, a
null
is
returned.
Example:
employees.firstOrDefault()
last
Iterates over the source elements, and if a predicate function is specified, then the last
element returning a
true
result is yielded. Otherwise, if no predicate function is specified,
the last operator simply returns the last element in the collection.
An
InvalidOperationException
is thrown if no element matches the predicate or if the
source collection is empty.
Example:
employees.last()
lastOrDefault
Iterates over the source elements, and if a predicate function is specified, then the last
element returning a
true
result is yielded. If no predicate function is specified, the
lastOrDefault
operator simply returns the last element in the collection.
If no element matches the predicate or if the source sequence is empty, a
null
is
returned.
Example:
employees.lastOrDefault()
single
Iterates over the source elements and returns the single element that returns
true
from
the predicate function. If no predicate function is specified, the single operator simply
returns the single element of the collection.
An
InvalidOperationException
is thrown if the source sequence is empty or contains no
matching element or more than one matching element.
Example:
employees.single()
singleOrDefault
Iterates over the source elements and returns the single element that returns
true
from the predicate function. If no predicate function is specified, the
singleOrDefault
operator simply returns the single element of the collection.
An
InvalidOperationException
is thrown if the source sequence contains more than
one matching element. If no element matches the predicate or if the source sequence is
empty,
null
is returned.
Example:
employees.singleOrDefault()
elementAt
The
List.get()
method is used to obtain the element at the specified
index
if the
collection is a
List
. Otherwise, the elements in the collection are iterated
index
number
of times, and the element found at the specified position is returned.
An
IndexOutOfBoundException
is thrown if the index is less than zero or greater than or
equal to the number of elements in the collection.
Example:
employees.elementAt(12)
(
continued
)