【问题标题】:Merge two lists of objects in Dart在 Dart 中合并两个对象列表
【发布时间】:2021-09-04 12:03:51
【问题描述】:

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

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

【问题讨论】:

标签: list flutter object dart merge


【解决方案1】:
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

【讨论】:

    【解决方案2】:

    首先为Persons 列表定义一个类:

    class PersonList{
      List<Person> _personList = [];
    
      get personList{
        return [..._personList];
      }
    
      void addToList(Person person){
        for(int i=0; i<_personList.length; i++){
          if(_personList[i].name == person.name){
            _personList[i].counter = _personList[i].counter + person.counter;
            return;
          }
        }
        _personList.add(person);
        return;
      }
    }
    

    然后,您可以创建它的新实例并将一些条目添加到列表中:

    PersonList theList = new PersonList();
    theList.addToList(Person(name:"Ben", counter: 2));
        print(theList.personList[0].counter);
        theList.addToList(Person(name:"Ben", counter: 5));
        print(theList.personList[0].counter);
    

    请随意使用addToList 方法。

    【讨论】:

      猜你喜欢
      • 2014-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-23
      • 1970-01-01
      • 2018-04-21
      • 2021-09-10
      • 1970-01-01
      相关资源
      最近更新 更多