elementAtOrDefaultE method
Returns the element at the specified index or a default value of one is not found.
Iterates over the entire enumerable until it reaches the element on the
iteration matching the given index
. elementAtE will then return that
value. If the iteration reaches the end of the enumerable before arriving
at index
, the value of defaultValue
will be returned instead. If
defaultValue
is not supplied, the returned value will be null
.
If the underlying collection is a ListEnumerable
, this method will instead
short-circuit into an indexer call to the List
as an O(1) operation. If
index
is greater than or equal to the length of the list, defaultValue
will be returned instead.
The elementAtOrDefaultE method will short-circuit after reaching the
element at index
and will not iterate further over the enumerable. In
the worst case, it will iterate over the entire enumerable.
Implementation
T elementAtOrDefaultE(int index, {T defaultValue}) {
RangeError.checkNotNegative(index);
if (this is ListEnumerable) {
if (index >= this.length) return defaultValue;
return (this as ListEnumerable)[index];
}
final iterator = this.iterator;
int currentIndex = 0;
while (iterator.moveNext()) {
if (currentIndex == index) return iterator.current;
currentIndex++;
}
return defaultValue;
}