集合是dart中的一个元素集合。
例如,一个List是以插入顺序存储项目的集合之一。
Dart集合的数字之和例子
我们有多种方法可以对数字集合进行求和。
List. reduce() 方法是用元素的迭代来减少元素的集合,并应用函数。
在这里,该函数将每个元素从列表中加入。
int reduce(int Function(int, int) combine)
下面是一个例子
main() {
List lists = [1, 2, 3, 6, 8];
var sum = lists.reduce((value, current) => value + current);
print(sum);
print(lists);
}
输出
20
[1, 2, 3, 6, 8]
列表折叠方法是另一种减少元素集合的方法,用一些函数来实现。
T fold(T initialValue, T Function(T, int) combine)
第一个参数是初始值,第二个参数是一个组合函数。
下面是一个程序实例
main() {
List lists = [1, 2, 3, 6, 8];
int sum = lists.fold(0, (previous, current) => previous + current);
print(sum);
print(lists);
}
输出
20
[1, 2, 3, 6, 8]
- 集合总和属性
collection.dart模块在列表对象上提供了sum属性。
获取一个数字的总和是很容易和快速的。
下面是一个程序代码
import 'package:collection/collection.dart';
main() {
List lists = [1, 2, 3, 6, 8];
int sum = lists.sum;
print(sum);
print(lists);
}
计算列表中对象的总和属性值
这个例子在一个雇员对象的列表中找到雇员工资的总和。让我们来创建一个雇员对象。
我们有多种方法可以通过属性值对对象进行求和。
class Employee {
final int id;
final String name;
final int salary;
final DateTime joinDate;
Employee(this.id, this.name, this.salary, this.joinDate);
Map toJson() =>
{"id": id, "name": name, "salary": salary, "doj": joinDate.toString()};
}
第一种方法,使用map方法遍历列表,并应用reduce函数对当前和之前的值进行求和。
int result = employees
.map((item) => item.salary)
.reduce((value, current) => value + current);
第二种方式,使用fold方法迭代并按属性键对对象列表进行求和
double result1 =
employees.fold(0, (sum, element) => sum.toDouble() + element.salary);
下面是一个示例程序
class Employee {
final int id;
final String name;
final int salary;
final DateTime joinDate;
Employee(this.id, this.name, this.salary, this.joinDate);
Map toJson() =>
{"id": id, "name": name, "salary": salary, "doj": joinDate.toString()};
}
void main() {
final e1 =
Employee(11, 'Erwin', 9000, DateTime.parse("2020-06-21 00:00:00.000"));
final e2 =
Employee(21, 'Andrew', 70000, DateTime.parse("2021-07-23 00:00:00.000"));
final e3 =
Employee(4, 'Mark', 8000, DateTime.parse("2017-08-24 00:00:00.000"));
final e4 =
Employee(12, 'Otroc', 5000, DateTime.parse("2022-12-05 00:00:00.000"));
final List employees = [e1, e2, e3, e4];
int result = employees
.map((item) => item.salary)
.reduce((value, current) => value + current);
print(result); //92000
double result1 =
employees.fold(0, (sum, element) => sum.toDouble() + element.salary);
print(result1); //92000
}