Last method

T Last ({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, Last 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 Last method will always iterate through the entire enumerable.

Implementation

T Last({Condition<T> condition}) {
  final iterator = this.iterator;
  if (!iterator.moveNext()) throw EmptyEnumerableError();

  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 ElementNotFoundError();
}