singleE method

T singleE ([Condition<T> condition ])

Returns the single element in the element, optionally matching a condition.

If condition is omitted, singleE will return the single value in this enumerable. If the enumerable is empty, or if the enumerable contains more than one element, an EnumerableError is thrown.

In this scenario, the singleE function will short-circuit after iterating a maximum of two elements into the enumerable.

If condition is supplied, singleE will iterate over the entire enumerable, applying the condition function to each element. At the end of the iteration, if a single element matches the condition, that element is returned. If no elements match the condition, or if more than one element matches the condition, an EnumerableError is thrown.

In this scenario, the singleE function will short-circuit after finding a second element that matches the condition. In the worst-case scenario, singleE will iterate over the entire enumerable.

Implementation

T singleE([Condition<T> condition]) {
  final _iterator = this.iterator;

  if (!_iterator.moveNext()) {
    throw EnumerableError.isEmpty();
  }

  bool valueSet = false;
  T value;

  if (condition != null) {
    do {
      if (condition(_iterator.current)) {
        if (valueSet) {
          throw EnumerableError.ambiguousMatch();
        }

        value = _iterator.current;
        valueSet = true;
      }
    } while (_iterator.moveNext());

    if (!valueSet) throw EnumerableError.elementNotFound();

    return value;
  }

  do {
    if (valueSet) {
      throw EnumerableError.tooMany();
    }

    value = _iterator.current;
    valueSet = true;
  } while (_iterator.moveNext());

  if (!valueSet) throw UnexpectedStateError();

  return value;
}