【问题标题】:Compare two Lists of Objects List A & B and store in another List C in dart比较两个对象列表 A 和 B 并存储在 dart 中的另一个列表 C 中
【发布时间】:2020-09-26 17:48:18
【问题描述】:

我正在尝试比较两个列表,allCategoriesselecetdCategories,如果列表中有类似的项目 selecetdCategoriesallCategories ,我应该首先将现有的存储在列表 orderPreferences 中,然后,我附加不存在的。我实际上对 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 中的两个对象列表的解决方案是什么?

【问题讨论】:

  • 如何使用地图。 allCategoriesMap 和 selecetdCategoriesMap 因为你有 id。然后迭代最小的映射并在另一个映射中查看它的值,将其存储在结果中并从两个映射中删除条目。然后,您可以将两个地图中的所有剩余部分推送到 resultList
  • @pranavprashant,我该如何删除,你谈到的,我还是很困惑:\,欢迎回答

标签: arrays list object dart


【解决方案1】:

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

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

List finalList = selectedCategories + allWithoutSelected;

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

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

【讨论】:

  • 感谢您的回答,它实际上接近我想要的,但令人惊讶的是有重复,我认为我们必须在allWithoutSelected上使用一个集合@
  • 尝试使用这个finalList.toSet().toList();,但没有成功,它仍然显示重复。
  • 谢谢大家,我错过了添加 Equatable,认为这是一个替代方案,我添加了,一切运行良好。谢谢大佬
猜你喜欢
  • 2021-06-27
  • 1970-01-01
  • 2022-12-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多