lastE method

T lastE ({Condition<T> condition })

Returns the last element in the enumerable, optionally matching a specified condition.

Iterates through the enumerable a returns the last element found that matches the specified condition. If condition is omitted, lastE will return the last element of the enumerable.

If the enumerable is empty, an EmptyEnumerableError will be thrown. If condition is provided but iteration reaches the end of the enumerable before an element is found, an ElementNotFoundError will be thrown.

The lastE method will always iterate through the entire enumerable.

Implementation

T lastE({Condition<T> condition}) {
  final iterator = this.iterator;
  if (!iterator.moveNext()) throw EnumerableError.isEmpty();

  T value;
  bool valueFound = false;
  do {
    if (condition == null || condition(iterator.current)) {
      value = iterator.current;
      valueFound = true;
    }
  } while (iterator.moveNext());

  if (valueFound) return value;

  throw EnumerableError.elementNotFound();
}