I have a list of items containing unique and repeating IDs, I want to sum the prices and display the number of the repeating IDs
class Model{
int id,price,count;
Model(this.id,this.price,this.count);
}
List<Model> list1 = [
Model(1,5000,10),
Model(2,1000,20),
Model(1,5000,5),
Model(2,5000,10),
];
List<Model> list2 = [];
I need the second list to be like this
list2 = [
Model(1,10000,15),
Model(2,6000,30),
];
CodePudding user response:
try this :
void main() {
int sum = 0;
List<Model> list1 = [
Model(1, 5000, 10),
Model(2, 1000, 20),
Model(1, 5000, 5),
Model(2, 5000, 10),
];
List<Model> list2 = modelsWithoutRepeatingIdsButSumOfPricesAndAmount(
list1); // [Model(1,10000,15), Model(2,6000,30),]
}
List<Model> modelsWithoutRepeatingIdsButSumOfPricesAndAmount(
List<Model> modelList) {
Map<int, Model> map = {};
for (int index = 0; index < modelList.length; index = 1) {
Model current = modelList[index];
map[current.id] ??= Model(current.id, 0, 0);
map[current.id]!.price = current.price;
map[current.id]!.count = current.count;
}
return map.values.toList();
}
class Model {
int id, price, count;
Model(this.id, this.price, this.count);
}
CodePudding user response:
Use reduce method to get the sum of a list
var total = [1, 2, 3].reduce((a, b) => a b);
If you don't want to use reduce method you can also use .fold() there are couple more you can get them by importing dart collections package.