lastOrDefaultE method

T lastOrDefaultE ({Condition<T> condition, T defaultValue })

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, lastOrDefaultE will return the last element of the enumerable.

If the enumerable is empty, or if condition is provided but iteration reaches the end of the enumerable before an element is found, the value specified by defaultValue will be returned instead. If defaultValue is omitted, the returned value will be null.

The lastOrDefaultE method will always iterate through the entire enumerable.

Implementation

T lastOrDefaultE({Condition<T> condition, T defaultValue}) {
  final iterator = this.iterator;
  if (!iterator.moveNext()) return defaultValue;

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

  if (valueFound) return value;

  return defaultValue;
}