list - 在 Dart 中合并两个对象列表

标签 list flutter object dart merge

我的对象有一个参数名称和一个参数计数器。这些对象存储在列表中。我列表中的某些项目具有重复的参数“名称”。我想删除列表中的重复项并将该重复项的计数器添加到 duplicate-objects 参数。

class Person{ 
Person({this.name, this.counter)};
  String name;
  int counter;
}

List<Person> theList = [];

theList.add(Person(name:"Ben", counter: 2);
theList.add(Person(name:"Ben", counter: 5);

//I need a function that changes the List to show Ben with counter 7

最佳答案

class Person{ 
  final String name;
  int counter;
  Person({required this.name, required this.counter});
}

extension on List<Person> {
  void addPerson({required String name, required int counter}) {
    if (isNotEmpty) {
      try {
        var person = firstWhere((p) => p.name == name);
        person.counter += counter;
      } catch(e) { 
        add(Person(name:name, counter: counter));
      }
    } else {
      add(Person(name:name, counter: counter));
    }
  }
}

void main() {
  var theList = <Person>[];

  theList.addPerson(name:"Lucho", counter: 4);
  theList.addPerson(name:"Ben", counter: 2);
  theList.addPerson(name:"Ben", counter: 5);  
  
  print(theList);
  print(theList.length);
  print("${theList[1].name} - ${theList[1].counter}");  
}

结果:

[Instance of 'Person', Instance of 'Person']
2
Ben - 7

关于list - 在 Dart 中合并两个对象列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68057377/

相关文章:

python - 循环遍历一组 Python 数字或一组字母是否更快?

python - 在python中生成函数列表

flutter - 如何实现多种颜色的多范围日历?

javascript - 我不清楚JavaScript函数/对象的结构

c# - 在 C# 中优化列表性能

python - 从列表中选择的最佳方式

flutter - 图像资源在 Web 上加载良好但在移动设备上加载不佳

flutter - 如何将 Flutter 中的一个小部件与另一个小部件叠加,不透明度设置为相乘?

python - pickle 和搁置有什么区别?

c# - cSharp 中的对象创建程序集