sumBy method

double sumBy(
  1. num selector(
    1. T element
    )
)

Calculates the sum of the selected values from all elements in the collection.

Applies the selector function to each element of the collection to obtain a numeric value and then sums these values to produce a cumulative result.

Parameters: selector (Function(T element)): A function that maps each element to a numeric value to be summed.

Returns: double: The sum of the selected values from all elements in the collection.

Example:

List<int> numbers = [1, 2, 3, 4, 5];
double result = numbers.sumBy((n) => n * 2); // Output: 30.0, as it sums 2, 4, 6, 8, and 10

Implementation

double sumBy(num selector(T element)) {
  double sum = 0.0;
  for (var current in this) {
    sum += selector(current);
  }

  return sum;
}