ElementAtOrDefault 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
. ElementAt 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
.
The ElementAtOrDefault 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 ElementAtOrDefault(int index, {T defaultValue}) {
assert(index >= 0);
final iterator = this.iterator;
int currentIndex = 0;
while (iterator.moveNext()) {
if (currentIndex == index) return iterator.current;
currentIndex++;
}
return defaultValue;
}