FirstOrDefault method

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

Returns the first element in the enumerable or a default value if there is none, optionally matching a specified condition.

Begins iteration of the enumerable, but then returns the first element found that matches the specified condition. If condition is omitted, FirstOrDefault will return the first 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.

If condition is provided, the FirstOrDefault method short-circuits the first time condition returns true and will not iterate further over the enumerable. In the worst case, it will iterate over the entire enumerable.

If condition is omitted, the FirstOrDefault method will always only visit the first element in the enumerable, making it run in constant time regardless of iteration length. Returns the first element in the enumerable or a default value if there is none.

Implementation

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

  do {
    if (condition(iterator.current)) return iterator.current;
  } while (iterator.moveNext());

  return defaultValue;
}