gpt4 book ai didi

arrays - 比较两个对象列表A和B的列表,并存储在 Dart 中的另一个列表C中

转载 作者:行者123 更新时间:2023-12-03 04:46:11 25 4
gpt4 key购买 nike

我正在尝试比较两个列表 allCategories selecetdCategories ,如果列表 selecetdCategories allcategory 中存在相似的项目,那么我应该先在列表中先存储现有项,然后再将它存储在List 中我附上不存在的内容。实际上,我对StackOverflow上的现有问题进行了一些研究,但我无法说明问题。

例如,每个列表具有以下项目:
allCategories :

  • 农业
  • 意见
  • 教育
  • 旅游
  • 教育
  • 文化
  • selecetdCategories :
  • 农业
  • 教育
  • 旅游

  • 然后,这就是我期望的orderPreferences列表中的内容项目应首先插入selectedCategories列表项目,然后再添加不存在的项目,例如:
  • 农业
  • 教育
  • 旅游
  • 意见
  • 教育
  • 文化

  • 下面是我当前的代码:
    class Model {
    int id;
    String name;

    Model({this.name, this.id});
    }

    void main() {
    List<Model> allCategories = List();
    allCategories.add(Model(id: 1, name: 'Agriculture'));
    allCategories.add(Model(id: 2, name: 'Opinions'));
    allCategories.add(Model(id: 3, name: 'Education'));
    allCategories.add(Model(id: 4, name: 'Tourism'));
    allCategories.add(Model(id: 5, name: 'Education'));
    allCategories.add(Model(id: 6, name: 'Culture'));

    List<Model> selecetdCategories = List();
    selecetdCategories.add(Model(id: 1, name: 'Agriculture'));
    selecetdCategories.add(Model(id: 5, name: 'Education'));
    selecetdCategories.add(Model(id: 4, name: 'Tourism'));

    List<Model> orderPreferences = List();

    for (var i = 0; i < allCategories.length; i++) {
    if (allCategories.contains(Model(
    id: selecetdCategories[i].id, name: selecetdCategories[i].name))) {
    orderPreferences
    .add(Model(id: allCategories[i].id, name: allCategories[i].name));
    }
    orderPreferences
    .add(Model(id: allCategories[i].id, name: allCategories[i].name));
    }

    for (var i = 0; i < orderPreferences.length; i++) {
    print(' name : ${orderPreferences[i].name}');
    }
    }

    但是,运行时出现异常:
     Uncaught Error: RangeError (index): Index out of range: index should
    be less than 3: 3

    比较dart中2个对象列表的解决方案是什么?

    最佳答案

    您的示例的可能解决方案之一:

    List allWithoutSelected = allCategories.where((item) => !selectedCategories.contains(item)).toList();   

    List finalList = selectedCategories + allWithoutSelected;

    我在这里所做的是首先过滤未选择的模型,然后将selectedCategories列表与allWithoutSelected连接起来。这样,顺序是正确的,并且没有重复项。

    为了使 contains方法起作用,您需要在模型中覆盖compare运算符或使其扩展为Equatable: https://pub.dev/packages/equatable

    关于arrays - 比较两个对象列表A和B的列表,并存储在 Dart 中的另一个列表C中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62250606/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com