Dart中对嵌套数据类使用fold求SelectedProductServices的count总和
Dart 嵌套列表count字段求和实现
你原有代码存在几处需要调整的逻辑:
getSum方法未传入OrderStructure实例作为参数,无法正常访问数据- 内层fold累加时没有读取
SelectedProductServices的count属性,直接对服务实例做加法会触发类型错误 - 对
products做map后得到的是每个商品对应的服务count总和列表,还需要额外做一次全局累加才能得到最终总和 getSum方法返回值定义为void与实际返回值冲突,需要修改为int类型
最简实现方案(两层fold嵌套)
int getSum(OrderStructure order) { // 第一层fold遍历所有商品,初始总和为0 return order.products.fold(0, (totalSum, currentProduct) { // 第二层fold累加当前商品下所有服务的count值 return totalSum + currentProduct.services.fold(0, (productSum, currentService) => productSum + currentService.count); }); }
修正后的完整可运行代码
void main() { OrderStructure order = OrderStructure('test', <SelectedProducts>[ SelectedProducts(1, <SelectedProductServices>[ const SelectedProductServices(1, 100, 1), const SelectedProductServices(1, 500, 1), ]) ]); // 调用求和方法,输出预期值600 print(getSum(order)); } int getSum(OrderStructure order) { return order.products.fold(0, (total, product) => total + product.services.fold(0, (productTotal, service) => productTotal + service.count ) ); } class OrderStructure { final String title; final List<SelectedProducts> products; const OrderStructure(this.title, this.products); } class SelectedProducts { final int id; final List<SelectedProductServices> services; SelectedProducts(this.id, this.services); @override bool operator ==(other) => other is SelectedProducts && other.id == id; @override int get hashCode => id.hashCode; } class SelectedProductServices { final int id; final int count; final int cost; const SelectedProductServices(this.id, this.count, this.cost); }
内容的提问来源于stack exchange,提问作者DolDurma
相关产品推荐
相关产品推荐

