首页 > 解决方案 > 如何在飞镖列表中获取重复值的总和?

问题描述

我想获得重复值的总和并将它们放在另一个列表中.. 有可能吗?

List list = [1, 1 , 2, 3,2];
List newList = [2,4,3];

标签: arrayslistsortingflutterdart

解决方案


当然,这是可能的。您可以定义一个临时列表以防止列表中出现重复项。尝试这个:

List list = [1, 1, 2, 3, 2];
List tempList = [];
List newList = [2, 4, 3];

for (var item in list) {
  if (!tempList.contains(item)) {
    newList.add(list.where((e) => e == item).length * item);
    tempList.add(item);
  }
}

推荐阅读